<?php

namespace App\Services;

use App\Models\License;
use App\Models\Product;
use App\Services\InvoiceService;
use Illuminate\Support\Facades\Auth;

class LicenseAutoRegistrationService
{
    protected $purchaseCodeService;
    protected $invoiceService;

    public function __construct(PurchaseCodeService $purchaseCodeService, InvoiceService $invoiceService)
    {
        $this->purchaseCodeService = $purchaseCodeService;
        $this->invoiceService = $invoiceService;
    }

    /**
     * Automatically register a license for the authenticated user
     * if the purchase code is valid and not already registered
     *
     * @param string $purchaseCode
     * @param int|null $productId
     * @return array ['success' => bool, 'license' => License|null, 'message' => string]
     */
    public function autoRegisterLicense(string $purchaseCode, ?int $productId = null): array
    {
        $user = Auth::user();

        if (!$user) {
            return [
                'success' => false,
                'license' => null,
                'message' => 'User must be authenticated'
            ];
        }

        // Check if user already has this license
        $existingLicense = License::where('purchase_code', $purchaseCode)
            ->where('user_id', $user->id)
            ->first();

        if ($existingLicense) {
            return [
                'success' => true,
                'license' => $existingLicense,
                'message' => 'License already exists for this user'
            ];
        }

        // Verify the purchase code
        $verificationResult = $this->purchaseCodeService->verifyRawCode($purchaseCode, $productId);

        if (!$verificationResult['success']) {
            return [
                'success' => false,
                'license' => null,
                'message' => $verificationResult['message'] ?? 'Invalid purchase code'
            ];
        }

        // Determine product ID from verification result or provided parameter
        $licenseProductId = $productId;

        if (!$licenseProductId && isset($verificationResult['product_id'])) {
            $licenseProductId = $verificationResult['product_id'];
        }

        if (!$licenseProductId) {
            return [
                'success' => false,
                'license' => null,
                'message' => 'Could not determine product for this purchase code'
            ];
        }

        // Verify product exists
        $product = Product::find($licenseProductId);
        if (!$product) {
            return [
                'success' => false,
                'license' => null,
                'message' => 'Product not found'
            ];
        }

        // Create the license
        $license = License::create([
            'purchase_code' => $purchaseCode,
            'product_id' => $licenseProductId,
            'user_id' => $user->id,
            'license_type' => 'regular',
            'status' => 'active',
            'support_expires_at' => isset($verificationResult['support_expires_at'])
                ? $verificationResult['support_expires_at']
                : null,
        ]);

        // Create initial invoice
        $this->invoiceService->createInitialInvoice($license);

        // Decrease product stock
        $product->decreaseStock();

        return [
            'success' => true,
            'license' => $license,
            'message' => 'License registered successfully'
        ];
    }

    /**
     * Check if a purchase code is valid without registering it
     *
     * @param string $purchaseCode
     * @param int|null $productId
     * @return array ['valid' => bool, 'message' => string, 'existing_license' => License|null]
     */
    public function checkPurchaseCode(string $purchaseCode, ?int $productId = null): array
    {
        $user = Auth::user();

        if (!$user) {
            return [
                'valid' => false,
                'message' => 'User must be authenticated',
                'existing_license' => null
            ];
        }

        // Check if user already has this license
        $existingLicense = License::where('purchase_code', $purchaseCode)
            ->where('user_id', $user->id)
            ->first();

        if ($existingLicense) {
            return [
                'valid' => true,
                'message' => 'License already exists for this user',
                'existing_license' => $existingLicense
            ];
        }

        // Verify the purchase code
        $verificationResult = $this->purchaseCodeService->verifyRawCode($purchaseCode, $productId);

        if (!$verificationResult['success']) {
            return [
                'valid' => false,
                'message' => $verificationResult['message'] ?? 'Invalid purchase code',
                'existing_license' => null
            ];
        }

        return [
            'valid' => true,
            'message' => 'Purchase code is valid',
            'existing_license' => null
        ];
    }
}