<?php

namespace App\Jobs;

use App\Models\TrackingExport;
use Carbon\Carbon;
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 UpdateExportStatusJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        private int $trackingExportId,
        private string $status,
        private ?string $errorMessage,
        private ?Carbon $completedAt
    ) {
        $this->onQueue('tracking');
    }

    public function handle(): void
    {
        try {
            $trackingExport = TrackingExport::findOrFail($this->trackingExportId);
            
            $updateData = [
                'export_status' => $this->status,
            ];

            if ($this->errorMessage !== null) {
                $updateData['error_message'] = $this->errorMessage;
            }

            if ($this->completedAt !== null) {
                $updateData['completed_at'] = $this->completedAt;
            } elseif (in_array($this->status, ['completed', 'failed'])) {
                $updateData['completed_at'] = now();
            }

            $trackingExport->update($updateData);
        } catch (\Exception $e) {
            Log::error('Failed to update export status', [
                'tracking_export_id' => $this->trackingExportId,
                'status' => $this->status,
                'error' => $e->getMessage(),
            ]);
            
            throw $e;
        }
    }

    public function failed(\Throwable $exception): void
    {
        Log::error('UpdateExportStatusJob failed permanently', [
            'tracking_export_id' => $this->trackingExportId,
            'status' => $this->status,
            'exception' => $exception->getMessage(),
        ]);
    }
}