<?php

namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleSpecType;
use Mtc\MercuryDataModels\VehicleStandardEquipment;

class YammaYapEquipmentImport implements ToCollection, WithHeadingRow
{
    public const REQUIRED_HEADERS = ['cdk_number', 'interior_features', 'exterior_features'];

    public int $imported = 0;
    public int $deleted = 0;
    public int $skippedRows = 0;
    public array $skippedUuids = [];

    public function __construct(private string $delimiter = ',')
    {
    }

    public function collection(Collection $rows): void
    {
        foreach ($rows as $row) {
            $cdkNumber = trim((string) ($row['cdk_number'] ?? ''));
            if (empty($cdkNumber)) {
                $this->skippedRows++;
                continue;
            }

            $vehicle = Vehicle::query()->where('uuid', $cdkNumber)->first();
            if (!$vehicle) {
                $this->skippedRows++;
                $this->skippedUuids[] = $cdkNumber;
                continue;
            }

            $this->deleted += VehicleStandardEquipment::query()
                ->where('vehicle_id', $vehicle->id)
                ->where('vehicle_type', 'vehicle')
                ->where(fn ($q) => $q->whereNull('category')->orWhereIn('category', ['Interior', 'Exterior']))
                ->delete();

            $this->upsertFeatures($vehicle, (string) ($row['interior_features'] ?? ''), 'Interior');
            $this->upsertFeatures($vehicle, (string) ($row['exterior_features'] ?? ''), 'Exterior');
        }
    }

    private function upsertFeatures(Vehicle $vehicle, string $features, string $category): void
    {
        if (empty(trim($features))) {
            return;
        }

        collect(explode($this->delimiter, $features))
            ->map(fn (string $description) => trim($description))
            ->filter()
            ->each(function (string $description) use ($vehicle, $category) {
                VehicleStandardEquipment::query()->updateOrCreate(
                    [
                        'vehicle_id' => $vehicle->id,
                        'vehicle_type' => 'vehicle',
                        'description' => $description,
                    ],
                    [
                        'type' => VehicleSpecType::STANDARD_EQUIPMENT->value,
                        'category' => $category,
                        'updated_at' => now(),
                    ]
                );

                $this->imported++;
            });
    }
}
