<?php

namespace App\Imports;

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 Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class VehicleImport implements ToCollection, WithHeadingRow
{
    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)
        };

        $model = $this->processRow($row);
        $this->storeUnmappedTaxonomy($model);
        return $model;
    }

    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,
            };
        }
    }
}
