<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\CarMake;
use App\Models\CarModel;
use App\Models\CarYear;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class CarDataSeeder extends Seeder
{
    public function run(): void
    {
        $jsonPath = database_path('data/car_makes_models_years.json');
        
        if (!File::exists($jsonPath)) {
            throw new \Exception('JSON file not found: ' . $jsonPath);
        }
        
        $json = File::get($jsonPath);
        $data = json_decode($json, true);
        
        if (!$data || !isset($data['makes'])) {
            throw new \Exception('Invalid JSON structure');
        }
        
        foreach ($data['makes'] as $makeName => $models) {
            $make = CarMake::firstOrCreate(
                ['name' => $makeName],
                [
                    'name' => $makeName, 
                    'slug' => Str::slug($makeName),
                    'is_active' => true
                ]
            );
            
            foreach ($models as $modelName => $years) {
                $carModel = CarModel::firstOrCreate(
                    [
                        'car_make_id' => $make->id, 
                        'name' => $modelName
                    ],
                    [
                        'car_make_id' => $make->id, 
                        'name' => $modelName, 
                        'slug' => Str::slug($makeName . '-' . $modelName),
                        'is_active' => true
                    ]
                );
                
                foreach ($years as $year) {
                    CarYear::firstOrCreate(
                        [
                            'car_model_id' => $carModel->id, 
                            'year' => $year
                        ],
                        [
                            'car_model_id' => $carModel->id, 
                            'year' => $year,
                            'is_active' => true
                        ]
                    );
                }
            }
        }
    }
}
