<?php

namespace App\Imports;

use App\Facades\Settings;
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 Mtc\MercuryDataModels\Vehicle;

class VehicleImportWithoutHeadingRow implements ToCollection
{
    use DispatchesJobs;
    use MapsTaxonomies;
    use Traits\VehicleImportFlow;

    protected static array $vehicleFillable = [];

    private ?ImportMap $import_map = null;

    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): ?Vehicle
    {
        try {
            return $this->processRow($this->mapBasedOnImportMap($source));
        } catch (\Exception $exception) {
            $this->incrementFailed();
            Log::error(tenant('id') . ' - ' . $exception->getMessage(), [
                'data' => $source,
            ]);
            return null;
        }
    }

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

    public function validateHeadings(array $headings): void
    {
        $expected = $this->expectedColumnCount();
        $on_file = count($headings);
        if ($expected !== $on_file) {
            throw new \Exception("Column count mismatch - expected $expected, got $on_file");
        }
    }

    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 expectedColumnCount(): int
    {
        return $this->import_map->fields
            ->filter(fn($field) => empty($field['data']['is_static']))
            ->pluck('on_file')
            ->count();
    }
}
