<?php

declare(strict_types=1);

namespace App\Jobs;

use App\DTOs\Import\ImportResultDto;
use App\Enums\ImportType;
use App\Services\Import\ImportService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Cache;

class ProcessImportJob implements ShouldQueue
{
    use Queueable;

    /**
     * @param  array<string, string|null>  $columnMapping
     */
    public function __construct(
        public ImportType $importType,
        public string $filePath,
        public array $columnMapping,
        public int $userId,
    ) {}

    public function handle(ImportService $importService): void
    {
        $rows = $importService->readRows($this->filePath);
        $mappedRows = $importService->mapRows($rows, $this->columnMapping);
        $result = $importService->import($this->importType, $mappedRows, $this->userId);

        Cache::put(
            $this->cacheKey(),
            $result->toArray(),
            now()->addHour(),
        );

        if (file_exists($this->filePath)) {
            unlink($this->filePath);
        }
    }

    public function cacheKey(): string
    {
        return "import_result_{$this->userId}";
    }

    public static function getCachedResult(int $userId): ?ImportResultDto
    {
        $cached = Cache::get("import_result_{$userId}");

        if (! is_array($cached)) {
            return null;
        }

        return new ImportResultDto(
            total: (int) ($cached['total'] ?? 0),
            imported: (int) ($cached['imported'] ?? 0),
            skipped: (int) ($cached['skipped'] ?? 0),
            failed: (int) ($cached['failed'] ?? 0),
            errors: $cached['errors'] ?? [],
        );
    }
}
