<?php

namespace App\Imports;

use App\Exports\VehicleExport;
use App\Jobs\CreateAIVehicleDescriptions;
use App\Models\ImportMap;
use App\Traits\MapsTaxonomies;
use App\VehicleSpec\Jobs\FetchVehicleListSpecData;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithStartRow;

class VehicleImport implements ToCollection, WithHeadingRow, WithStartRow
{
    use DispatchesJobs;
    use MapsTaxonomies;
    use Traits\VehicleImportFlow;

    protected static array $vehicleFillable = [];

    private ?ImportMap $import_map;

    private string $dealershipMatchValue = 'location_stock';

    private array $additional_tasks = [];

    public function __construct(
        private readonly ?string $importType = '',
        private ?Collection $dealerships = null,
        private ?Collection $makes = null,
        private ?Collection $models = null,
        private ?Collection $fuel_types = null,
        private ?Collection $body_styles = null,
        private ?Collection $drivetrains = null,
        private ?Collection $transmissions = null
    ) {
        $this->loadRelationships();
    }

    public function model(array $source)
    {
        $row = match ($this->importType) {
            'default' => $source,
            default => $this->mapBasedOnImportMap($source)
        };

        try {
            $model = $this->processRow($row);
            if ($model) {
                $this->storeUnmappedTaxonomy($model);
            }
            return $model;
        } catch (\Exception $exception) {
            $this->incrementFailed();
            Log::error(tenant('id') . ' - ' . $exception->getMessage(), [
                'data' => $source,
            ]);
            return null;
        }
    }

    public function startRow(): int
    {
        return 2;
    }

    public function headingRow(): int
    {
        return 1;
    }

    public function validateHeadings(array $headings): void
    {
        $missing = array_diff($this->getExpectedHeadings(), $headings);
        if (!empty($missing)) {
            throw new \Exception('Columns not found in file: ' . implode(', ', $missing));
        }
    }

    protected function getDetailsForTaxonomyMap(array $record): array
    {
        return $record;
    }

    public function collection(Collection $collection): void
    {
        $this->triggerAdditionalTasks(
            $collection->map(fn(Collection $row) => $this->model($row->toArray()))->filter()
        );
    }

    private function triggerAdditionalTasks(Collection $vehicles): void
    {
        foreach ($this->additional_tasks as $task) {
            match ($task) {
                'vehicle-specs' => FetchVehicleListSpecData::dispatch($vehicles),
                'ai-content' => CreateAIVehicleDescriptions::dispatch(false, $vehicles),
                default => null,
            };
        }
    }

    private function getExpectedHeadings(): array
    {
        if ($this->importType === 'default') {
            return (new VehicleExport())->headings();
        }

        return $this->import_map->fields
            ->filter(fn($field) => empty($field['data']['is_static']))
            ->pluck('on_file')
            ->toArray();
    }
}
