<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\License;
use App\Services\EnvatoService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class ProductApiController extends Controller
{
    protected EnvatoService $envatoService;

    public function __construct(EnvatoService $envatoService)
    {
        $this->envatoService = $envatoService;
    }

    /**
     * Product lookup by purchase code (for ticket creation)
     */
    public function lookupByPurchaseCode(Request $request): JsonResponse
    {
        $request->validate([
            'purchase_code' => 'required|string'
        ]);

        try {
            $purchaseCode = trim($request->purchase_code);

            // First, check if this purchase code exists in our database
            $existingLicense = License::with('product')->where('purchase_code', $purchaseCode)->first();

            if ($existingLicense && $existingLicense->product) {
                return response()->json([
                    'success' => true,
                    'product_slug' => $existingLicense->product->slug,
                    'product_name' => $existingLicense->product->name,
                    'license_exists' => true,
                    'license_id' => $existingLicense->id
                ]);
            }

            // If not found in database, try Envato API
            $sale = $this->envatoService->verifyPurchase($purchaseCode);

            if ($sale) {
                $productSlug = data_get($sale, 'item.slug');
                $productName = data_get($sale, 'item.name');

                return response()->json([
                    'success' => true,
                    'product_slug' => $productSlug,
                    'product_name' => $productName,
                    'license_exists' => false,
                    'sale' => $sale
                ]);
            }

            return response()->json([
                'success' => false,
                'message' => 'Invalid purchase code'
            ], 400);

        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Unable to verify purchase code'
            ], 500);
        }
    }
}
