<?php

namespace Database\Seeders;

use App\Models\Category;
use App\Models\Product;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class ProductSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get all categories (including subcategories) for random assignment
        $categories = Category::all();

        if ($categories->isEmpty()) {
            $this->command->warn('No categories found. Please create categories first.');

            return;
        }

        // Product name templates
        $productNames = [
            'Premium', 'Luxury', 'Classic', 'Modern', 'Elegant', 'Comfort', 'Deluxe', 'Ultra',
            'Professional', 'Elite', 'Supreme', 'Royal', 'Signature', 'Designer', 'Boutique',
            'Silk', 'Cotton', 'Bamboo', 'Memory Foam', 'Gel', 'Cooling', 'Orthopedic', 'Therapeutic',
        ];

        $productTypes = [
            'Pillow', 'Bedding Set', 'Mattress', 'Comforter', 'Blanket', 'Sheet Set',
            'Duvet Cover', 'Pillowcase', 'Mattress Topper', 'Bed Skirt', 'Quilt', 'Throw',
            'Pillow Protector', 'Mattress Pad', 'Bed Frame', 'Headboard', 'Nightstand', 'Dresser',
        ];

        $descriptions = [
            'High-quality product designed for ultimate comfort and durability.',
            'Premium materials ensure long-lasting performance and satisfaction.',
            'Crafted with attention to detail for the perfect sleeping experience.',
            'Innovative design meets traditional craftsmanship for exceptional quality.',
            'Experience luxury and comfort with this carefully selected product.',
            'Made from the finest materials to provide unmatched comfort.',
            'Transform your bedroom into a sanctuary of relaxation and style.',
            'Engineered for optimal support and comfort throughout the night.',
        ];

        $khmerDescriptions = [
            'ផលិតផលគុណភាពខ្ពស់ដែលរចនាឡើងសម្រាប់ផាសុកភាព និងភាពធន់នឹងការប្រើប្រាស់។',
            'សម្ភារៈប្រណិតធានាបាននូវការអនុវត្តយូរអង្វែង និងការពេញចិត្ត។',
            'ធ្វើឡើងដោយការយកចិត្តទុកដាក់លម្អិតសម្រាប់បទពិសោធន៍គេងល្អបំផុត។',
            'ការរចនាច្នៃប្រឌិតជួបជាមួយការធ្វើដៃពីប្រពៃណីសម្រាប់គុណភាពពិសេស។',
            'សូមជួបជាមួយភាពប្រណិត និងផាសុកភាពជាមួយផលិតផលដែលបានជ្រើសរើសដោយប្រុងប្រយ័ត្ន។',
            'ធ្វើឡើងពីសម្ភារៈល្អបំផុតដើម្បីផ្តល់ផាសុកភាពដែលមិនអាចប្រៀបផ្ទឹមបាន។',
            'បំប្លែងបន្ទប់គេងរបស់អ្នកទៅជាកន្លែងសម្រាក និងរចនា។',
            'វិស្វកម្មសម្រាប់ការគាំទ្រ និងផាសុកភាពល្អបំផុតពេញមួយយប់។',
        ];

        $this->command->info('Creating 1000 dummy products...');
        $bar = $this->command->getOutput()->createProgressBar(1000);
        $bar->start();

        // Use chunking to avoid memory issues
        $chunkSize = 100;
        $totalProducts = 1000;

        for ($i = 0; $i < $totalProducts; $i += $chunkSize) {
            $products = [];

            for ($j = 0; $j < $chunkSize && ($i + $j) < $totalProducts; $j++) {
                $namePrefix = $productNames[array_rand($productNames)];
                $productType = $productTypes[array_rand($productTypes)];
                $productName = $namePrefix.' '.$productType.' '.($i + $j + 1);

                // Random category assignment
                $randomCategory = $categories->random();
                $categoryId = $randomCategory->id;
                $categoryCode = $randomCategory->code;

                // Price between $10 and $1000
                $price = round(mt_rand(1000, 100000) / 100, 2);

                // 30% chance of being on sale
                $onSale = mt_rand(1, 100) <= 30;
                $originalPrice = $onSale ? round($price * (1 + mt_rand(10, 50) / 100), 2) : 0;

                // 85% chance of being in stock
                $inStock = mt_rand(1, 100) <= 85;

                // Random number of images (1-5)
                $imageCount = mt_rand(1, 5);
                $images = [];
                for ($k = 0; $k < $imageCount; $k++) {
                    $images[] = '/storage/uploads/products/product-'.($i + $j + 1).'-image-'.($k + 1).'.jpg';
                }

                $description = $descriptions[array_rand($descriptions)];
                $descriptionKm = $khmerDescriptions[array_rand($khmerDescriptions)];

                $products[] = [
                    'name' => $productName,
                    'name_km' => 'ផលិតផល '.($i + $j + 1),
                    'price' => $price,
                    'original_price' => $originalPrice,
                    'category' => $categoryCode,
                    'category_id' => $categoryId,
                    'description' => $description.' '.$productName.' is perfect for your home.',
                    'description_km' => $descriptionKm.' '.$productName.' ល្អសម្រាប់ផ្ទះរបស់អ្នក។',
                    'short_description' => $namePrefix.' '.$productType,
                    'short_description_km' => 'ផលិតផល '.$namePrefix,
                    'in_stock' => $inStock,
                    'on_sale' => $onSale,
                    'images' => json_encode($images),
                    'created_at' => now()->subDays(mt_rand(0, 365)),
                    'updated_at' => now()->subDays(mt_rand(0, 30)),
                ];
            }

            // Bulk insert for better performance
            DB::table('products')->insert($products);
            $bar->advance(count($products));
        }

        $bar->finish();
        $this->command->newLine();
        $this->command->info('Successfully created 1000 products!');
    }
}
