<?php

namespace App\Jobs;

use App\Models\Import;
use App\Models\ImportEvent;
use App\Services\Import\ImportServiceV2;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ProcessLargeImportJob implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 3600; // 1 hour

    public $tries = 3;

    /**
     * Create a new job instance.
     */
    public function __construct(
        public Import $import,
        public ?int $userId = null
    ) {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        Log::info('ProcessLargeImportJob started', [
            'import_id' => $this->import->id,
            'user_id' => $this->userId,
        ]);

        try {
            $user = $this->userId ? \App\Models\User::find($this->userId) : null;

            $service = app(ImportServiceV2::class);
            $results = $service->process($this->import, $user);

            Log::info('ProcessLargeImportJob completed', [
                'import_id' => $this->import->id,
                'results' => $results,
            ]);

            ImportEvent::create([
                'import_id' => $this->import->id,
                'user_id' => $this->userId,
                'event' => 'queue_job_completed',
                'level' => 'info',
                'message' => sprintf(
                    'Queued import completed: %d imported, %d skipped, %d invalid',
                    $results['imported'],
                    $results['skipped'],
                    $results['invalid']
                ),
                'context' => $results,
            ]);
        } catch (\Throwable $e) {
            Log::error('ProcessLargeImportJob failed', [
                'import_id' => $this->import->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            $this->import->update(['status' => 'failed']);

            ImportEvent::create([
                'import_id' => $this->import->id,
                'user_id' => $this->userId,
                'event' => 'queue_job_failed',
                'level' => 'error',
                'message' => $e->getMessage(),
            ]);

            throw $e;
        }
    }

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

        $this->import->update(['status' => 'failed']);

        ImportEvent::create([
            'import_id' => $this->import->id,
            'user_id' => $this->userId,
            'event' => 'queue_job_permanently_failed',
            'level' => 'error',
            'message' => 'Import job failed after maximum retries: '.$exception->getMessage(),
        ]);
    }
}
