<?php

namespace App\Jobs;

use App\Models\ProductImport;
use App\Services\ProductImportService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ProcessProductImportJob implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 1;

    public int $timeout = 600;

    public function __construct(
        public ProductImport $productImport
    ) {
        $this->onQueue('default');
    }

    public function handle(ProductImportService $importService): void
    {
        $import = $this->productImport->fresh();
        if (!$import || !$import->isPending()) {
            return;
        }

        $path = $import->getResolvedFilePath();
        if ($path === null || !file_exists($path)) {
            $import->update([
                'status' => ProductImport::STATUS_FAILED,
                'message' => 'Stored file not found.',
                'report' => [
                    'errors' => [
                        'File not found: ' . $import->file_path,
                        'Resolved path: ' . ($path ?? 'null'),
                    ],
                ],
                'completed_at' => now(),
            ]);
            return;
        }

        $import->update([
            'status' => ProductImport::STATUS_PROCESSING,
            'started_at' => now(),
        ]);

        try {
            $report = $importService->run($path, $import->user_id);
            $imported = $report['imported'];
            $skipped = $report['skipped'];
            $variantsImported = $report['variants_imported'] ?? 0;
            $errors = $report['errors'] ?? [];

            $message = "Imported {$imported} product(s)";
            if ($variantsImported > 0) {
                $message .= " with {$variantsImported} variant(s)";
            }
            if ($skipped > 0) {
                $message .= ". {$skipped} row(s) skipped.";
            }
            if (!empty($errors)) {
                $message .= " " . count($errors) . " error(s).";
            }

            $import->update([
                'status' => ProductImport::STATUS_COMPLETED,
                'message' => $message,
                'report' => $report,
                'completed_at' => now(),
            ]);
        } catch (\Throwable $e) {
            Log::error('ProcessProductImportJob failed', [
                'import_id' => $import->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            $import->update([
                'status' => ProductImport::STATUS_FAILED,
                'message' => 'Import failed: ' . $e->getMessage(),
                'report' => [
                    'imported' => 0,
                    'skipped' => 0,
                    'variants_imported' => 0,
                    'errors' => [$e->getMessage()],
                ],
                'completed_at' => now(),
            ]);
        }
    }
}
