<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Ingredient;
use App\Models\Category;
use App\Models\Product;
use App\Models\Recipe;
use App\Models\RecipeIngredient;
use App\Models\ScoopYield;
use App\Models\Branch;
use Illuminate\Support\Facades\DB;

class IceCreamRecipesTestSeeder extends Seeder
{
    /**
     * Comprehensive test data for ice cream recipes and products
     * Includes realistic recipes, pricing, and complete system testing
     */
    public function run(): void
    {
        DB::transaction(function () {
            echo "🍦 Starting Ice Cream Recipes Test Seeder...\n\n";

            // Step 1: Create Ingredients
            $ingredients = $this->createIngredients();
            echo "✅ Created " . count($ingredients) . " ingredients\n";

            // Step 2: Create Categories
            $categories = $this->createCategories();
            echo "✅ Created " . count($categories) . " categories\n";

            // Step 3: Create Products
            $products = $this->createProducts($categories);
            echo "✅ Created " . count($products) . " products\n";

            // Step 4: Create Recipes
            $recipes = $this->createRecipes($products, $ingredients);
            echo "✅ Created " . count($recipes) . " recipes\n";

            // Step 5: Create Scoop Yields
            $scoopYields = $this->createScoopYields($ingredients);
            echo "✅ Created " . count($scoopYields) . " scoop yield configurations\n";

            echo "\n🎉 Ice Cream Recipes Test Seeder completed successfully!\n";
            $this->printSummary($products, $recipes);
        });
    }

    private function createIngredients(): array
    {
        $ingredientsData = [
            // Dairy & Cream
            ['name' => 'Full Cream Milk Powder (FCMP)', 'code' => 'FCMP', 'unit' => 'grams', 'cost_per_unit' => 0.50, 'category' => 'Dairy'],
            ['name' => 'Skimmed Milk Powder (SKMP)', 'code' => 'SKMP', 'unit' => 'grams', 'cost_per_unit' => 0.45, 'category' => 'Dairy'],
            ['name' => 'Fresh Cream', 'code' => 'CREAM', 'unit' => 'grams', 'cost_per_unit' => 0.80, 'category' => 'Dairy'],
            ['name' => 'Whole Milk', 'code' => 'MILK', 'unit' => 'ml', 'cost_per_unit' => 0.15, 'category' => 'Dairy'],

            // Sweeteners
            ['name' => 'White Sugar', 'code' => 'SUGAR', 'unit' => 'grams', 'cost_per_unit' => 0.10, 'category' => 'Sweeteners'],
            ['name' => 'Brown Sugar', 'code' => 'BROWN-SUGAR', 'unit' => 'grams', 'cost_per_unit' => 0.12, 'category' => 'Sweeteners'],
            ['name' => 'Honey', 'code' => 'HONEY', 'unit' => 'grams', 'cost_per_unit' => 0.25, 'category' => 'Sweeteners'],

            // Stabilizers & Emulsifiers
            ['name' => 'CMC (Carboxymethyl Cellulose)', 'code' => 'CMC', 'unit' => 'grams', 'cost_per_unit' => 2.50, 'category' => 'Stabilizers'],
            ['name' => 'GMS (Glycerol Monostearate)', 'code' => 'GMS', 'unit' => 'grams', 'cost_per_unit' => 1.80, 'category' => 'Emulsifiers'],
            ['name' => 'Cremofon', 'code' => 'CREMOFON', 'unit' => 'grams', 'cost_per_unit' => 2.00, 'category' => 'Emulsifiers'],

            // Flavors
            ['name' => 'Vanilla Extract', 'code' => 'VANILLA', 'unit' => 'grams', 'cost_per_unit' => 8.00, 'category' => 'Flavors'],
            ['name' => 'Cocoa Powder', 'code' => 'COCOA', 'unit' => 'grams', 'cost_per_unit' => 1.50, 'category' => 'Flavors'],
            ['name' => 'Strawberry Puree', 'code' => 'STRAWBERRY', 'unit' => 'grams', 'cost_per_unit' => 0.60, 'category' => 'Flavors'],
            ['name' => 'Mango Puree', 'code' => 'MANGO', 'unit' => 'grams', 'cost_per_unit' => 0.70, 'category' => 'Flavors'],
            ['name' => 'Pistachio Paste', 'code' => 'PISTACHIO', 'unit' => 'grams', 'cost_per_unit' => 3.50, 'category' => 'Flavors'],
            ['name' => 'Chocolate Chips', 'code' => 'CHOC-CHIPS', 'unit' => 'grams', 'cost_per_unit' => 0.90, 'category' => 'Mix-ins'],
            ['name' => 'Coffee Extract', 'code' => 'COFFEE', 'unit' => 'grams', 'cost_per_unit' => 1.20, 'category' => 'Flavors'],
            ['name' => 'Mint Extract', 'code' => 'MINT', 'unit' => 'grams', 'cost_per_unit' => 1.00, 'category' => 'Flavors'],
            ['name' => 'Caramel Sauce', 'code' => 'CARAMEL', 'unit' => 'grams', 'cost_per_unit' => 0.80, 'category' => 'Sauces'],
            ['name' => 'Oreo Crumbs', 'code' => 'OREO', 'unit' => 'grams', 'cost_per_unit' => 1.10, 'category' => 'Mix-ins'],

            // Nuts & Mix-ins
            ['name' => 'Roasted Almonds', 'code' => 'ALMONDS', 'unit' => 'grams', 'cost_per_unit' => 1.40, 'category' => 'Nuts'],
            ['name' => 'Crushed Peanuts', 'code' => 'PEANUTS', 'unit' => 'grams', 'cost_per_unit' => 0.70, 'category' => 'Nuts'],
            ['name' => 'Cookie Dough', 'code' => 'COOKIE-DOUGH', 'unit' => 'grams', 'cost_per_unit' => 1.30, 'category' => 'Mix-ins'],

            // Others
            ['name' => 'Water', 'code' => 'WATER', 'unit' => 'ml', 'cost_per_unit' => 0.001, 'category' => 'Base'],
            ['name' => 'Salt', 'code' => 'SALT', 'unit' => 'grams', 'cost_per_unit' => 0.05, 'category' => 'Seasoning'],
        ];

        $ingredients = [];
        foreach ($ingredientsData as $data) {
            $ingredient = Ingredient::create([
                'name' => $data['name'],
                'code' => $data['code'],
                'unit' => $data['unit'],
                'cost_per_unit' => $data['cost_per_unit'],
                'reorder_level' => 1000,
                'is_active' => true,
            ]);
            $ingredients[$data['code']] = $ingredient;
        }

        return $ingredients;
    }

    private function createCategories(): array
    {
        $categoriesData = [
            ['name' => 'Classic Ice Cream', 'slug' => 'classic', 'description' => 'Traditional ice cream flavors'],
            ['name' => 'Premium Ice Cream', 'slug' => 'premium', 'description' => 'Gourmet and specialty flavors'],
            ['name' => 'Fruit Ice Cream', 'slug' => 'fruit', 'description' => 'Refreshing fruit-based flavors'],
            ['name' => 'Specialty Mix-ins', 'slug' => 'specialty', 'description' => 'Unique combinations with mix-ins'],
        ];

        $categories = [];
        foreach ($categoriesData as $data) {
            $category = Category::create([
                'name' => $data['name'],
                'slug' => $data['slug'],
                'description' => $data['description'],
                'is_active' => true,
                'sort_order' => count($categories) + 1,
            ]);
            $categories[$data['slug']] = $category;
        }

        return $categories;
    }

    private function createProducts(array $categories): array
    {
        $productsData = [
            // Classic Ice Cream
            [
                'category' => 'classic',
                'name' => 'Vanilla',
                'slug' => 'vanilla',
                'description' => 'Rich and creamy vanilla ice cream',
                'base_price' => 3.50,
                'scoop_price' => 2.00,
            ],
            [
                'category' => 'classic',
                'name' => 'Chocolate',
                'slug' => 'chocolate',
                'description' => 'Decadent chocolate ice cream',
                'base_price' => 3.50,
                'scoop_price' => 2.00,
            ],
            [
                'category' => 'classic',
                'name' => 'Coffee',
                'slug' => 'coffee',
                'description' => 'Bold coffee-flavored ice cream',
                'base_price' => 3.75,
                'scoop_price' => 2.25,
            ],

            // Premium Ice Cream
            [
                'category' => 'premium',
                'name' => 'Pistachio',
                'slug' => 'pistachio',
                'description' => 'Premium pistachio ice cream with real nuts',
                'base_price' => 5.00,
                'scoop_price' => 3.00,
            ],
            [
                'category' => 'premium',
                'name' => 'Salted Caramel',
                'slug' => 'salted-caramel',
                'description' => 'Sweet and salty caramel perfection',
                'base_price' => 4.50,
                'scoop_price' => 2.75,
            ],
            [
                'category' => 'premium',
                'name' => 'Mint Chocolate Chip',
                'slug' => 'mint-choc-chip',
                'description' => 'Refreshing mint with chocolate chips',
                'base_price' => 4.25,
                'scoop_price' => 2.50,
            ],

            // Fruit Ice Cream
            [
                'category' => 'fruit',
                'name' => 'Strawberry',
                'slug' => 'strawberry',
                'description' => 'Fresh strawberry ice cream',
                'base_price' => 3.75,
                'scoop_price' => 2.25,
            ],
            [
                'category' => 'fruit',
                'name' => 'Mango',
                'slug' => 'mango',
                'description' => 'Tropical mango ice cream',
                'base_price' => 3.75,
                'scoop_price' => 2.25,
            ],

            // Specialty Mix-ins
            [
                'category' => 'specialty',
                'name' => 'Cookies & Cream',
                'slug' => 'cookies-cream',
                'description' => 'Vanilla with Oreo cookie pieces',
                'base_price' => 4.50,
                'scoop_price' => 2.75,
            ],
            [
                'category' => 'specialty',
                'name' => 'Cookie Dough',
                'slug' => 'cookie-dough',
                'description' => 'Vanilla with chunks of cookie dough',
                'base_price' => 4.75,
                'scoop_price' => 2.85,
            ],
        ];

        $products = [];
        foreach ($productsData as $data) {
            $product = Product::create([
                'category_id' => $categories[$data['category']]->id,
                'name' => $data['name'],
                'slug' => $data['slug'],
                'description' => $data['description'],
                'base_price' => $data['base_price'],
                'scoop_price' => $data['scoop_price'],
                'is_active' => true,
                'max_scoops' => 6,
            ]);
            $products[$data['slug']] = $product;
        }

        return $products;
    }

    private function createRecipes(array $products, array $ingredients): array
    {
        $recipesData = [
            // Vanilla Recipe (Base: ~3000g total)
            'vanilla' => [
                'name' => 'Classic Vanilla Ice Cream',
                'batch_size' => 3000,
                'yield_scoops' => 42, // ~71g per scoop
                'preparation_time' => 120, // minutes
                'ingredients' => [
                    'FCMP' => 450,
                    'SKMP' => 400,
                    'SUGAR' => 1100,
                    'CMC' => 2,
                    'GMS' => 36,
                    'CREMOFON' => 6,
                    'VANILLA' => 1,
                    'CREAM' => 1000,
                    'WATER' => 5, // for mixing
                ],
                'instructions' => [
                    'Mix all dry ingredients (FCMP, SKMP, Sugar, CMC, GMS, Cremofon)',
                    'Heat cream to 60°C',
                    'Slowly add dry mixture while stirring continuously',
                    'Pasteurize at 85°C for 30 seconds',
                    'Cool rapidly to 4°C',
                    'Add vanilla extract',
                    'Age mixture for 4 hours',
                    'Churn in ice cream machine',
                    'Freeze at -18°C',
                ],
            ],

            // Chocolate Recipe
            'chocolate' => [
                'name' => 'Rich Chocolate Ice Cream',
                'batch_size' => 3000,
                'yield_scoops' => 42,
                'preparation_time' => 130,
                'ingredients' => [
                    'FCMP' => 400,
                    'SKMP' => 350,
                    'SUGAR' => 1000,
                    'COCOA' => 200,
                    'CMC' => 2,
                    'GMS' => 36,
                    'CREMOFON' => 6,
                    'CREAM' => 1000,
                    'WATER' => 6,
                ],
                'instructions' => [
                    'Sift cocoa powder with dry ingredients',
                    'Heat cream to 65°C',
                    'Add dry mixture gradually',
                    'Pasteurize at 85°C for 30 seconds',
                    'Cool to 4°C',
                    'Age for 4 hours',
                    'Churn and freeze',
                ],
            ],

            // Coffee Recipe
            'coffee' => [
                'name' => 'Coffee Ice Cream',
                'batch_size' => 3000,
                'yield_scoops' => 42,
                'preparation_time' => 125,
                'ingredients' => [
                    'FCMP' => 450,
                    'SKMP' => 400,
                    'SUGAR' => 1050,
                    'CMC' => 2,
                    'GMS' => 36,
                    'CREMOFON' => 6,
                    'COFFEE' => 50,
                    'CREAM' => 1000,
                    'WATER' => 6,
                ],
                'instructions' => [
                    'Dissolve coffee extract in warm cream',
                    'Mix dry ingredients',
                    'Combine and heat to 65°C',
                    'Pasteurize at 85°C',
                    'Cool and age',
                    'Churn and freeze',
                ],
            ],

            // Pistachio Recipe (Premium)
            'pistachio' => [
                'name' => 'Premium Pistachio Ice Cream',
                'batch_size' => 3000,
                'yield_scoops' => 40, // Slightly denser with nuts
                'preparation_time' => 140,
                'ingredients' => [
                    'FCMP' => 450,
                    'SKMP' => 380,
                    'SUGAR' => 1000,
                    'CMC' => 2,
                    'GMS' => 36,
                    'CREMOFON' => 6,
                    'PISTACHIO' => 120,
                    'ALMONDS' => 80,
                    'CREAM' => 920,
                    'WATER' => 6,
                ],
                'instructions' => [
                    'Grind pistachios and almonds to paste',
                    'Mix with cream',
                    'Add dry ingredients',
                    'Process and pasteurize',
                    'Cool and age',
                    'Churn with additional chopped nuts',
                    'Freeze',
                ],
            ],

            // Strawberry Recipe
            'strawberry' => [
                'name' => 'Fresh Strawberry Ice Cream',
                'batch_size' => 3000,
                'yield_scoops' => 42,
                'preparation_time' => 130,
                'ingredients' => [
                    'FCMP' => 420,
                    'SKMP' => 380,
                    'SUGAR' => 950,
                    'CMC' => 2,
                    'GMS' => 32,
                    'CREMOFON' => 6,
                    'STRAWBERRY' => 200,
                    'CREAM' => 1000,
                    'WATER' => 10,
                ],
                'instructions' => [
                    'Puree fresh strawberries',
                    'Mix dry ingredients',
                    'Combine with cream and strawberry puree',
                    'Pasteurize at 85°C',
                    'Cool rapidly',
                    'Age for 4 hours',
                    'Churn and freeze',
                ],
            ],

            // Mango Recipe
            'mango' => [
                'name' => 'Tropical Mango Ice Cream',
                'batch_size' => 3000,
                'yield_scoops' => 42,
                'preparation_time' => 125,
                'ingredients' => [
                    'FCMP' => 400,
                    'SKMP' => 370,
                    'SUGAR' => 920,
                    'CMC' => 2,
                    'GMS' => 32,
                    'CREMOFON' => 6,
                    'MANGO' => 250,
                    'CREAM' => 1010,
                    'WATER' => 10,
                ],
                'instructions' => [
                    'Use ripe mango puree',
                    'Mix with cream and sugar',
                    'Add stabilizers',
                    'Pasteurize',
                    'Cool and age',
                    'Churn and freeze',
                ],
            ],

            // Salted Caramel Recipe
            'salted-caramel' => [
                'name' => 'Salted Caramel Ice Cream',
                'batch_size' => 3000,
                'yield_scoops' => 41,
                'preparation_time' => 150,
                'ingredients' => [
                    'FCMP' => 430,
                    'SKMP' => 380,
                    'SUGAR' => 900,
                    'BROWN-SUGAR' => 150,
                    'CMC' => 2,
                    'GMS' => 36,
                    'CREMOFON' => 6,
                    'CARAMEL' => 180,
                    'SALT' => 8,
                    'CREAM' => 900,
                    'WATER' => 8,
                ],
                'instructions' => [
                    'Make caramel sauce with brown sugar',
                    'Mix dry ingredients',
                    'Combine all ingredients',
                    'Pasteurize',
                    'Cool',
                    'Age for 6 hours for caramel to develop',
                    'Churn and freeze',
                ],
            ],

            // Mint Chocolate Chip
            'mint-choc-chip' => [
                'name' => 'Mint Chocolate Chip Ice Cream',
                'batch_size' => 3000,
                'yield_scoops' => 41,
                'preparation_time' => 135,
                'ingredients' => [
                    'FCMP' => 440,
                    'SKMP' => 390,
                    'SUGAR' => 1080,
                    'CMC' => 2,
                    'GMS' => 36,
                    'CREMOFON' => 6,
                    'MINT' => 12,
                    'CHOC-CHIPS' => 140,
                    'CREAM' => 886,
                    'WATER' => 8,
                ],
                'instructions' => [
                    'Mix base ingredients',
                    'Add mint extract',
                    'Pasteurize and cool',
                    'Age for 4 hours',
                    'Churn',
                    'Add chocolate chips during last minute of churning',
                    'Freeze',
                ],
            ],

            // Cookies & Cream
            'cookies-cream' => [
                'name' => 'Cookies & Cream Ice Cream',
                'batch_size' => 3000,
                'yield_scoops' => 40,
                'preparation_time' => 130,
                'ingredients' => [
                    'FCMP' => 450,
                    'SKMP' => 400,
                    'SUGAR' => 1050,
                    'CMC' => 2,
                    'GMS' => 36,
                    'CREMOFON' => 6,
                    'VANILLA' => 2,
                    'OREO' => 200,
                    'CREAM' => 846,
                    'WATER' => 8,
                ],
                'instructions' => [
                    'Make vanilla base',
                    'Pasteurize and cool',
                    'Age for 4 hours',
                    'Crush Oreo cookies',
                    'Churn base',
                    'Add cookie crumbs in last 2 minutes',
                    'Freeze',
                ],
            ],

            // Cookie Dough
            'cookie-dough' => [
                'name' => 'Cookie Dough Ice Cream',
                'batch_size' => 3000,
                'yield_scoops' => 39,
                'preparation_time' => 145,
                'ingredients' => [
                    'FCMP' => 440,
                    'SKMP' => 390,
                    'SUGAR' => 1020,
                    'CMC' => 2,
                    'GMS' => 36,
                    'CREMOFON' => 6,
                    'VANILLA' => 2,
                    'COOKIE-DOUGH' => 250,
                    'CHOC-CHIPS' => 80,
                    'CREAM' => 766,
                    'WATER' => 8,
                ],
                'instructions' => [
                    'Make vanilla base',
                    'Pasteurize and cool',
                    'Age for 4 hours',
                    'Prepare cookie dough pieces (frozen)',
                    'Churn base',
                    'Add cookie dough and chocolate chips',
                    'Freeze immediately',
                ],
            ],
        ];

        $recipes = [];
        foreach ($recipesData as $productSlug => $recipeData) {
            if (!isset($products[$productSlug])) {
                continue;
            }

            // Create Recipe
            $recipe = Recipe::create([
                'product_id' => $products[$productSlug]->id,
                'name' => $recipeData['name'],
                'batch_size' => $recipeData['batch_size'],
                'yield_scoops' => $recipeData['yield_scoops'],
                'preparation_time' => $recipeData['preparation_time'],
                'instructions' => json_encode($recipeData['instructions']),
                'is_active' => true,
            ]);

            // Add Recipe Ingredients
            foreach ($recipeData['ingredients'] as $ingredientCode => $quantity) {
                if (isset($ingredients[$ingredientCode])) {
                    RecipeIngredient::create([
                        'recipe_id' => $recipe->id,
                        'ingredient_id' => $ingredients[$ingredientCode]->id,
                        'quantity' => $quantity,
                    ]);
                }
            }

            // Calculate cost
            $recipe->calculateCost();

            $recipes[$productSlug] = $recipe;
        }

        return $recipes;
    }

    private function createScoopYields(array $ingredients): array
    {
        // Define how many scoops you get per unit of each ingredient
        // This helps track ingredient usage per scoop
        $scoopYieldsData = [
            'FCMP' => ['quantity_per_unit' => 450, 'scoops_per_unit' => 42], // 450g yields 42 scoops
            'CREAM' => ['quantity_per_unit' => 1000, 'scoops_per_unit' => 42],
            'COCOA' => ['quantity_per_unit' => 200, 'scoops_per_unit' => 42],
            'STRAWBERRY' => ['quantity_per_unit' => 200, 'scoops_per_unit' => 42],
            'MANGO' => ['quantity_per_unit' => 250, 'scoops_per_unit' => 42],
        ];

        $scoopYields = [];
        foreach ($scoopYieldsData as $ingredientCode => $data) {
            if (isset($ingredients[$ingredientCode])) {
                $scoopYield = ScoopYield::create([
                    'ingredient_id' => $ingredients[$ingredientCode]->id,
                    'quantity_per_unit' => $data['quantity_per_unit'],
                    'scoops_per_unit' => $data['scoops_per_unit'],
                    'is_active' => true,
                ]);
                $scoopYields[] = $scoopYield;
            }
        }

        return $scoopYields;
    }

    private function printSummary(array $products, array $recipes): void
    {
        echo "\n" . str_repeat("=", 60) . "\n";
        echo "RECIPE COST SUMMARY\n";
        echo str_repeat("=", 60) . "\n\n";

        foreach ($recipes as $slug => $recipe) {
            echo sprintf("%-25s | Cost: $%.2f | Scoops: %d | Cost/Scoop: $%.2f\n",
                $recipe->name,
                $recipe->total_cost,
                $recipe->yield_scoops,
                $recipe->cost_per_scoop
            );
        }

        echo "\n" . str_repeat("=", 60) . "\n";
        echo "PRODUCT PRICING\n";
        echo str_repeat("=", 60) . "\n\n";

        foreach ($products as $slug => $product) {
            $recipe = $recipes[$slug] ?? null;
            $costPerScoop = $recipe ? $recipe->cost_per_scoop : 0;
            $margin = $product->scoop_price - $costPerScoop;
            $marginPercent = $costPerScoop > 0 ? ($margin / $costPerScoop) * 100 : 0;

            echo sprintf("%-25s | Price: $%.2f | Cost: $%.2f | Margin: $%.2f (%.0f%%)\n",
                $product->name,
                $product->scoop_price,
                $costPerScoop,
                $margin,
                $marginPercent
            );
        }

        echo "\n" . str_repeat("=", 60) . "\n\n";
    }
}
