<?php

namespace App\Services;

use App\Models\Code;
use Illuminate\Support\Facades\Log;

class CodeVerificationService
{
    private const MAX_ATTEMPTS = 5;

    /**
     * Verify a code by serial (QR or GUID)
     */
    public function verify(string $serial, string $ipAddress): array
    {
        // Find code by QR or GUID
        $code = Code::where('qr', $serial)
                    ->orWhere('guid', $serial)
                    ->first();

        if (!$code) {
            return [
                'status' => 'error',
                'message' => 'Invalid code. Please check and try again.',
                'is_lucky' => false,
                'code' => null,
            ];
        }

        // Increment attempts
        $code->increment('attempts');

        // Check if marked as fake or exceeded max attempts
        if ($code->status === 'fake' || $code->attempts >= self::MAX_ATTEMPTS) {
            $code->update(['status' => 'fake']);

            Log::warning('Counterfeit code detected', [
                'serial' => $serial,
                'ip' => $ipAddress,
                'attempts' => $code->attempts,
            ]);

            return [
                'status' => 'error',
                'message' => 'This code has been flagged as counterfeit. If you believe this is an error, please contact support.',
                'is_lucky' => false,
                'code' => $code,
            ];
        }

        // First-time verification (unused code)
        if ($code->status === 'unused') {
            $code->update([
                'status' => 'used',
                'lastverified' => now(),
                'ipv' => $ipAddress,
            ]);

            $message = 'Genuine product verified! This is your first verification.';

            if ($code->islucky) {
                $message = '🎉 Congratulations! This is a LUCKY CODE! You are eligible for our prize draw. Please fill in your details below.';
            }

            return [
                'status' => 'success',
                'message' => $message,
                'is_lucky' => $code->islucky,
                'code' => $code->load('product'),
            ];
        }

        // Already verified code
        $attemptInfo = "Attempt {$code->attempts} of " . self::MAX_ATTEMPTS;

        return [
            'status' => 'warning',
            'message' => "This code was already verified on {$code->lastverified->format('M d, Y')}. {$attemptInfo}",
            'is_lucky' => false,
            'code' => $code->load('product'),
        ];
    }

    /**
     * Get verification statistics
     */
    public function getStats(): array
    {
        return [
            'total' => Code::count(),
            'unused' => Code::where('status', 'unused')->count(),
            'used' => Code::where('status', 'used')->count(),
            'fake' => Code::where('status', 'fake')->count(),
            'lucky' => Code::where('islucky', true)->count(),
        ];
    }
}
