<?php

namespace App\Jobs;

use App\Models\Order;
use App\Services\Fraud\FraudDetectionService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class RunFraudChecksJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The number of times the job may be attempted.
     */
    public int $tries = 3;

    /**
     * The number of seconds to wait before retrying the job.
     */
    public int $backoff = 30;

    /**
     * Create a new job instance.
     */
    public function __construct(public Order $order) {}

    /**
     * Execute the job.
     */
    public function handle(FraudDetectionService $fraudService): void
    {
        try {
            $fraudService->analyze($this->order, async: false);

            // If review or rejected, notify admin
            $this->order->refresh();

            if (in_array($this->order->fraud_status, ['review', 'rejected'])) {
                $this->notifyAdmin();
            }
        } catch (\Exception $e) {
            Log::error('RunFraudChecksJob failed', [
                'order_id' => $this->order->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            throw $e;
        }
    }

    /**
     * Notify admin about flagged order via email.
     */
    private function notifyAdmin(): void
    {
        try {
            SendEmailJob::dispatch('Fraud Order Flagged', 'order', $this->order->id, [
                'ORDER_ID' => $this->order->id,
                'FRAUD_STATUS' => $this->order->fraud_status,
                'FRAUD_SCORE' => $this->order->fraud_score,
                'CLIENT_NAME' => $this->order->client?->first_name . ' ' . $this->order->client?->last_name,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to send fraud notification email', [
                'order_id' => $this->order->id,
                'error' => $e->getMessage(),
            ]);
        }
    }

    /**
     * Handle a job failure.
     */
    public function failed(\Throwable $exception): void
    {
        Log::error('RunFraudChecksJob permanently failed', [
            'order_id' => $this->order->id,
            'error' => $exception->getMessage(),
        ]);

        // Set fraud status to indicate check failure so order isn't stuck in "checking"
        $this->order->updateQuietly([
            'fraud_status' => 'approved',
            'fraud_checks' => [
                'error' => 'Fraud checks failed after retries: ' . $exception->getMessage(),
                'checked_at' => now()->toIso8601String(),
            ],
        ]);
    }
}
