<?php

namespace Database\Seeders;

use App\Models\Brand;
use App\Models\CarMake;
use App\Models\CarModel;
use App\Models\CarYear;
use App\Models\Category;
use App\Models\Product;
use App\Models\ProductImage;
use App\Models\User;
use App\Models\Vendor;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Spatie\Permission\Models\Role;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        // Create demo images first
        $this->call(DemoProductImagesSeeder::class);
        
        // Create roles
        $adminRole = Role::firstOrCreate(['name' => 'admin', 'guard_name' => 'web']);
        $vendorRole = Role::firstOrCreate(['name' => 'vendor', 'guard_name' => 'web']);
        $customerRole = Role::firstOrCreate(['name' => 'customer', 'guard_name' => 'web']);

        // Create admin user
        $admin = User::firstOrCreate(
            ['email' => 'admin@autoparts.com'],
            [
                'name' => 'Admin User',
                'username' => 'admin',
                'password' => Hash::make('password'),
                'email_verified_at' => now()
            ]
        );
        $admin->assignRole('admin');

        // Create vendor users
        $vendorData = [
            ['name' => 'John Smith', 'email' => 'vendor1@autoparts.com', 'username' => 'vendor1', 'shop' => 'Premium Auto Parts', 'city' => 'Los Angeles'],
            ['name' => 'Sarah Johnson', 'email' => 'vendor2@autoparts.com', 'username' => 'vendor2', 'shop' => 'Quality Car Parts', 'city' => 'Chicago'],
            ['name' => 'Mike Davis', 'email' => 'vendor3@autoparts.com', 'username' => 'vendor3', 'shop' => 'AutoZone Supplies', 'city' => 'Houston'],
        ];

        $vendors = [];
        foreach ($vendorData as $vd) {
            $user = User::firstOrCreate(
                ['email' => $vd['email']],
                [
                    'name' => $vd['name'],
                    'username' => $vd['username'],
                    'password' => Hash::make('password'),
                    'email_verified_at' => now()
                ]
            );
            $user->assignRole('vendor');
            $vendor = Vendor::firstOrCreate(
                ['user_id' => $user->id],
                [
                    'shop_name' => $vd['shop'],
                    'slug' => Str::slug($vd['shop']),
                    'description' => 'Quality auto parts from trusted supplier. We offer the best prices and fastest shipping for all your automotive needs.',
                    'city' => $vd['city'],
                    'country' => 'United States',
                    'status' => 'approved',
                    'commission_rate' => 10.00,
                ]
            );
            $vendors[] = $vendor;
        }

        // Create customer
        $customer = User::firstOrCreate(
            ['email' => 'customer@autoparts.com'],
            [
                'name' => 'Test Customer',
                'username' => 'customer1',
                'password' => Hash::make('password'),
                'email_verified_at' => now()
            ]
        );
        $customer->assignRole('customer');

        // Create categories with images
        $categoryData = [
            ['name' => 'Engine Parts', 'desc' => 'Engine components, gaskets, pistons, and more'],
            ['name' => 'Brakes & Rotors', 'desc' => 'Brake pads, rotors, calipers, and brake fluid'],
            ['name' => 'Suspension', 'desc' => 'Shocks, struts, springs, and suspension kits'],
            ['name' => 'Electrical', 'desc' => 'Batteries, alternators, starters, and sensors'],
            ['name' => 'Filters', 'desc' => 'Oil filters, air filters, fuel filters, and cabin filters'],
            ['name' => 'Exhaust', 'desc' => 'Mufflers, catalytic converters, and exhaust pipes'],
            ['name' => 'Transmission', 'desc' => 'Transmission parts, filters, and fluids'],
            ['name' => 'Body Parts', 'desc' => 'Bumpers, fenders, doors, and mirrors'],
        ];
        
        $categories = [];
        foreach ($categoryData as $i => $cat) {
            $categories[] = Category::firstOrCreate(
                ['slug' => Str::slug($cat['name'])],
                [
                    'name' => $cat['name'],
                    'description' => $cat['desc'],
                    'image' => 'categories/category_' . ($i + 1) . '.svg',
                    'sort_order' => $i + 1,
                    'is_active' => true
                ]
            );
        }

        // Create brands with images
        $brandNames = ['Bosch', 'ACDelco', 'Moog', 'Monroe', 'Denso', 'Gates', 'NGK', 'Dorman', 'Raybestos', 'KYB'];
        $brands = [];
        foreach ($brandNames as $i => $brandName) {
            $brands[] = Brand::firstOrCreate(
                ['slug' => Str::slug($brandName)],
                [
                    'name' => $brandName,
                    'logo' => 'brands/brand_' . ($i + 1) . '.svg',
                    'is_active' => true
                ]
            );
        }

        // Create car makes, models, years
        $carData = [
            'Toyota' => ['Camry' => [2018, 2019, 2020, 2021, 2022], 'Corolla' => [2018, 2019, 2020, 2021, 2022, 2023]],
            'Honda' => ['Civic' => [2018, 2019, 2020, 2021, 2022, 2023], 'Accord' => [2018, 2019, 2020, 2021, 2022]],
            'Ford' => ['F-150' => [2018, 2019, 2020, 2021, 2022, 2023], 'Mustang' => [2018, 2019, 2020, 2021, 2022]],
            'Chevrolet' => ['Silverado' => [2018, 2019, 2020, 2021, 2022], 'Malibu' => [2018, 2019, 2020, 2021, 2022]],
            'BMW' => ['3 Series' => [2018, 2019, 2020, 2021, 2022], '5 Series' => [2018, 2019, 2020, 2021, 2022]],
            'Mercedes-Benz' => ['C-Class' => [2018, 2019, 2020, 2021, 2022], 'E-Class' => [2018, 2019, 2020, 2021]],
        ];

        $allYears = [];
        foreach ($carData as $makeName => $models) {
            $make = CarMake::firstOrCreate(
                ['slug' => Str::slug($makeName)],
                ['name' => $makeName, 'is_active' => true]
            );
            foreach ($models as $modelName => $years) {
                $model = CarModel::firstOrCreate(
                    ['car_make_id' => $make->id, 'slug' => Str::slug($makeName . '-' . $modelName)],
                    ['name' => $modelName, 'is_active' => true]
                );
                foreach ($years as $year) {
                    $carYear = CarYear::firstOrCreate(
                        ['car_model_id' => $model->id, 'year' => $year],
                        ['is_active' => true]
                    );
                    $allYears[] = $carYear;
                }
            }
        }

        // Create products with images
        $productData = [
            ['name' => 'Bosch Iridium Spark Plug Set (4 Pack)', 'price' => 24.99, 'cat' => 0, 'brand' => 0, 'sku' => 'BOS-4417', 'stock' => 45],
            ['name' => 'ACDelco Professional Oil Filter', 'price' => 12.99, 'cat' => 4, 'brand' => 1, 'sku' => 'ACD-PF61E', 'stock' => 120],
            ['name' => 'Monroe OESpectrum Shock Absorber', 'price' => 89.99, 'cat' => 2, 'brand' => 3, 'sku' => 'MON-37278', 'stock' => 32],
            ['name' => 'Raybestos Element3 Brake Pads - Front', 'price' => 45.99, 'cat' => 1, 'brand' => 8, 'sku' => 'RAY-EHT699H', 'stock' => 67],
            ['name' => 'Denso Oxygen Sensor - OE Style', 'price' => 67.99, 'cat' => 3, 'brand' => 4, 'sku' => 'DEN-234-4622', 'stock' => 28],
            ['name' => 'Gates Timing Belt Kit with Water Pump', 'price' => 134.99, 'cat' => 0, 'brand' => 5, 'sku' => 'GAT-TCKWP298', 'stock' => 15],
            ['name' => 'NGK Ignition Coil Pack', 'price' => 52.99, 'cat' => 3, 'brand' => 6, 'sku' => 'NGK-U5098', 'stock' => 54],
            ['name' => 'Moog Front Lower Ball Joint', 'price' => 78.99, 'cat' => 2, 'brand' => 2, 'sku' => 'MOG-K6541', 'stock' => 38],
            ['name' => 'Dorman Radiator Cap - 16 PSI', 'price' => 8.99, 'cat' => 0, 'brand' => 7, 'sku' => 'DOR-54227', 'stock' => 89],
            ['name' => 'KYB Excel-G Strut Assembly', 'price' => 129.99, 'cat' => 2, 'brand' => 9, 'sku' => 'KYB-339241', 'stock' => 22],
            ['name' => 'Bosch Workshop Air Filter', 'price' => 18.99, 'cat' => 4, 'brand' => 0, 'sku' => 'BOS-S0130', 'stock' => 76],
            ['name' => 'ACDelco Advantage Brake Rotor', 'price' => 95.99, 'cat' => 1, 'brand' => 1, 'sku' => 'ACD-18A1705', 'stock' => 41],
            ['name' => 'Fel-Pro Exhaust Manifold Gasket Set', 'price' => 22.99, 'cat' => 5, 'brand' => 7, 'sku' => 'FEL-MS92467', 'stock' => 33],
            ['name' => 'ATP Automatic Transmission Filter Kit', 'price' => 38.99, 'cat' => 6, 'brand' => 5, 'sku' => 'ATP-B-241', 'stock' => 19],
            ['name' => 'Dorman Front Bumper Cover', 'price' => 189.99, 'cat' => 7, 'brand' => 7, 'sku' => 'DOR-FO1000563', 'stock' => 8],
            ['name' => 'Bosch Premium Cabin Air Filter', 'price' => 24.99, 'cat' => 4, 'brand' => 0, 'sku' => 'BOS-6040C', 'stock' => 62],
            ['name' => 'Monroe Quick-Strut Complete Assembly', 'price' => 159.99, 'cat' => 2, 'brand' => 3, 'sku' => 'MON-172287', 'stock' => 14],
            ['name' => 'NGK Laser Platinum Spark Plugs', 'price' => 32.99, 'cat' => 0, 'brand' => 6, 'sku' => 'NGK-6240', 'stock' => 95],
            ['name' => 'Moog Sway Bar Link Kit', 'price' => 34.99, 'cat' => 2, 'brand' => 2, 'sku' => 'MOG-K750083', 'stock' => 47],
            ['name' => 'Denso Alternator - Remanufactured', 'price' => 189.99, 'cat' => 3, 'brand' => 4, 'sku' => 'DEN-210-0438', 'stock' => 11],
        ];

        foreach ($productData as $i => $pd) {
            $vendor = $vendors[$i % count($vendors)];
            $salePrice = $i % 3 === 0 ? round($pd['price'] * 0.85, 2) : null;
            
            $product = Product::firstOrCreate(
                ['slug' => Str::slug($pd['name'])],
                [
                    'vendor_id' => $vendor->id,
                    'category_id' => $categories[$pd['cat']]->id,
                    'brand_id' => $brands[$pd['brand']]->id,
                    'name' => $pd['name'],
                    'short_description' => 'High quality ' . strtolower(explode(' - ', $pd['name'])[0]) . ' for your vehicle. OEM quality guaranteed.',
                    'description' => $this->getProductDescription($pd['name']),
                    'price' => $pd['price'],
                    'sale_price' => $salePrice,
                    'stock_quantity' => $pd['stock'],
                    'condition' => 'new',
                    'part_number' => $pd['sku'],
                    'sku' => $pd['sku'],
                    'is_active' => true,
                    'is_featured' => $i < 6,
                    'approval_status' => 'approved',
                    'weight' => round(rand(10, 500) / 10, 2),
                ]
            );
            
            // Add product images
            $imageIndex = ($i % 20) + 1;
            ProductImage::firstOrCreate(
                ['product_id' => $product->id, 'sort_order' => 1],
                [
                    'image_path' => 'products/product_' . $imageIndex . '.svg',
                ]
            );
            
            // Add secondary image for some products
            if ($i % 2 === 0) {
                $imageIndex2 = (($i + 5) % 20) + 1;
                ProductImage::firstOrCreate(
                    ['product_id' => $product->id, 'sort_order' => 2],
                    [
                        'image_path' => 'products/product_' . $imageIndex2 . '.svg',
                    ]
                );
            }
            
            // Attach car years
            $randomYears = collect($allYears)->random(min(8, count($allYears)))->pluck('id')->toArray();
            $product->carYears()->syncWithoutDetaching($randomYears);
        }

        $this->call([
            PermissionSeeder::class,
            CurrencySeeder::class,
            CarDataSeeder::class,
        ]);

        $this->command->info('========================================');
        $this->command->info('🎉 DEMO DATA SEEDED SUCCESSFULLY!');
        $this->command->info('========================================');
        $this->command->info('');
        $this->command->info('📧 Login Credentials:');
        $this->command->info('   Admin:    admin@autoparts.com / password');
        $this->command->info('   Vendor 1: vendor1@autoparts.com / password');
        $this->command->info('   Vendor 2: vendor2@autoparts.com / password');
        $this->command->info('   Vendor 3: vendor3@autoparts.com / password');
        $this->command->info('   Customer: customer@autoparts.com / password');
        $this->command->info('');
        $this->command->info('📦 Products: 20 demo products with images');
        $this->command->info('🏷️  Categories: 8 categories with images');
        $this->command->info('🏭 Brands: 10 brands with logos');
        $this->command->info('🚗 Car Data: 6 makes, 12 models, 60+ years');
        $this->command->info('');
        $this->command->info('⚠️  IMPORTANT: Run this command to link storage:');
        $this->command->info('   php artisan storage:link');
        $this->command->info('========================================');
    }
    
    private function getProductDescription($productName)
    {
        $descriptions = [
            'This premium quality part is manufactured to meet or exceed OEM specifications.',
            'Designed for optimal performance and long-lasting durability.',
            'Engineered with high-grade materials for reliable operation.',
            'Precision-manufactured for perfect fit and function.',
            'Backed by manufacturer warranty for peace of mind.',
        ];
        
        $features = [
            '• Direct OEM replacement',
            '• Easy installation - no modifications required',
            '• Rigorous quality testing',
            '• Corrosion-resistant coating',
            '• Meets or exceeds industry standards',
        ];
        
        return implode("\n\n", [
            $descriptions[array_rand($descriptions)],
            'Key Features:',
            implode("\n", $features)
        ]);
    }
}
