<?php

namespace App\Jobs;

use App\Models\Tenant\OcrJob;
use App\Services\Ai\OcrInvoiceService;
use App\Tenancy\TenantManager;
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\Storage;

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

    public int $tries = 2;
    public int $timeout = 120;

    public function __construct(public int $ocrJobId, public int $companyId) {}

    public function handle(OcrInvoiceService $svc, TenantManager $tenants): void
    {
        // Re-establish tenant context inside the queue worker
        $company = \App\Models\Central\Company::find($this->companyId);
        if (! $company) { return; }
        $tenants->setCurrent($company);

        $job = OcrJob::find($this->ocrJobId);
        if (! $job) return;

        $job->update(['status' => 'processing']);

        try {
            $absPath = Storage::disk('local')->path($job->file_path);
            $result = $svc->extract($absPath);
            $job->update([
                'status' => 'done',
                'result' => $result,
                'processed_at' => now(),
                'ai_provider' => 'claude',
            ]);
        } catch (\Throwable $e) {
            $job->update([
                'status' => 'failed',
                'error_message' => $e->getMessage(),
                'processed_at' => now(),
            ]);
            throw $e;
        }
    }

    public function failed(\Throwable $e): void
    {
        $job = OcrJob::find($this->ocrJobId);
        $job?->update(['status' => 'failed', 'error_message' => $e->getMessage()]);
    }
}
