<?php

namespace App\Imports;

use App\Jobs\AssignFilterFeatures;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Mtc\MercuryDataModels\FilterFeature;
use Mtc\MercuryDataModels\VehicleStandardEquipment;

class StandardEquipmentImport implements ToCollection, WithHeadingRow
{
    public function collection(Collection $rows): void
    {
        foreach ($rows as $row) {
            $description = (string) ($row['description'] ?? '');
            if (empty($description)) {
                continue;
            }

            VehicleStandardEquipment::query()
                ->where('description', $description)
                ->update(['category' => $row['category'] ?? null]);

            $friendlyName = trim((string) ($row['friendly_name'] ?? ''));
            if (empty($friendlyName)) {
                continue;
            }

            $feature = FilterFeature::where('name', $friendlyName)->first();

            if ($feature) {
                $terms = $feature->terms ?? [];
                if (!in_array($description, $terms)) {
                    $terms[] = $description;
                    $feature->terms = $terms;
                    $feature->exact_match = true;
                    $feature->save();
                }
            } else {
                $feature = FilterFeature::create([
                    'name' => $friendlyName,
                    'terms' => [$description],
                    'exact_match' => true,
                ]);
            }

            dispatch(new AssignFilterFeatures($feature));
        }
    }
}
