<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Category;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class CategoryDataSeeder extends Seeder
{
    public function run(): void
    {
        $jsonPath = database_path('data/auto_parts_categories.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['categories']) || !isset($data['subcategories'])) {
            throw new \Exception('Invalid JSON structure');
        }
        
        $sortOrder = 1;
        
        // First, create all main categories
        foreach ($data['categories'] as $categoryName) {
            $slug = Str::slug($categoryName);
            
            Category::firstOrCreate(
                ['slug' => $slug],
                [
                    'name' => $categoryName,
                    'slug' => $slug,
                    'description' => $categoryName . ' for all vehicle types.',
                    'sort_order' => $sortOrder++,
                    'is_active' => true,
                    'parent_id' => null
                ]
            );
        }
        
        // Then, create all subcategories
        foreach ($data['subcategories'] as $subcategory) {
            $parentSlug = $subcategory['category_slug'];
            $parent = Category::where('slug', $parentSlug)->first();
            
            if ($parent) {
                Category::firstOrCreate(
                    ['slug' => $subcategory['subcategory_slug']],
                    [
                        'name' => $subcategory['subcategory'],
                        'slug' => $subcategory['subcategory_slug'],
                        'description' => $subcategory['subcategory'] . ' for ' . $subcategory['category'] . '.',
                        'sort_order' => $sortOrder++,
                        'is_active' => true,
                        'parent_id' => $parent->id
                    ]
                );
            }
        }
    }
}
