<?php

namespace Database\Seeders;

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

class VanillaRecipeSeeder extends Seeder
{
    public function run(): void
    {
        $this->command->info('');
        $this->command->info('🍦 Vanilla Ice Cream Recipe Seeder');
        $this->command->info('═══════════════════════════════════════');
        $this->command->info('');

        DB::transaction(function () {
            // Step 1: Create Ingredients
            $this->command->info('📦 Creating ingredients...');
            $this->command->info('');

            $ingredients = [
                ['name' => 'Full Cream Milk Powder (FCMP)', 'sku' => 'FCMP', 'unit' => 'grams', 'cost_per_unit' => 0.50],
                ['name' => 'Skim Milk Powder (SKMP)', 'sku' => 'SKMP', 'unit' => 'grams', 'cost_per_unit' => 0.45],
                ['name' => 'White Sugar', 'sku' => 'SUGAR', 'unit' => 'grams', 'cost_per_unit' => 0.10],
                ['name' => 'CMC Stabilizer', 'sku' => 'CMC', 'unit' => 'grams', 'cost_per_unit' => 2.50],
                ['name' => 'GMS Emulsifier', 'sku' => 'GMS', 'unit' => 'grams', 'cost_per_unit' => 1.80],
                ['name' => 'Cremofon', 'sku' => 'CREMOFON', 'unit' => 'grams', 'cost_per_unit' => 2.00],
                ['name' => 'Vanilla Extract', 'sku' => 'VANILLA', 'unit' => 'grams', 'cost_per_unit' => 8.00],
                ['name' => 'Fresh Cream', 'sku' => 'CREAM', 'unit' => 'grams', 'cost_per_unit' => 0.80],
                ['name' => 'Water', 'sku' => 'WATER', 'unit' => 'ml', 'cost_per_unit' => 0.001],
            ];

            $createdIngredients = [];
            foreach ($ingredients as $ingredientData) {
                $ingredient = Ingredient::firstOrCreate(
                    ['sku' => $ingredientData['sku']],
                    [
                        'name' => $ingredientData['name'],
                        'unit' => $ingredientData['unit'],
                        'cost_per_unit' => $ingredientData['cost_per_unit'],
                        'is_active' => true,
                    ]
                );
                $createdIngredients[$ingredientData['sku']] = $ingredient;
                $this->command->info("  ✓ {$ingredient->name} - \${$ingredient->cost_per_unit}/{$ingredient->unit}");
            }

            $this->command->info('');

            // Step 2: Create Product Category
            $this->command->info('📁 Creating category...');
            $category = Category::firstOrCreate(
                ['name' => 'Ice Cream Flavours'],
                [
                    'slug' => 'ice-cream-flavours',
                    'description' => 'Ice cream flavour products',
                    'is_active' => true,
                ]
            );
            $this->command->info("  ✓ {$category->name}");
            $this->command->info('');

            // Step 3: Create Vanilla Product
            $this->command->info('🍨 Creating vanilla product...');
            $vanillaProduct = Product::firstOrCreate(
                ['slug' => 'classic-vanilla-ice-cream'],
                [
                    'name' => 'Classic Vanilla Ice Cream',
                    'category_id' => $category->id,
                    'description' => 'Premium vanilla ice cream made with real vanilla extract',
                    'base_price' => 3.50,
                    'scoop_price' => 2.00,
                    'is_active' => true,
                ]
            );
            $this->command->info("  ✓ {$vanillaProduct->name} - Base: \${$vanillaProduct->base_price} | Scoop: \${$vanillaProduct->scoop_price}");
            $this->command->info('');

            // Step 4: Create Recipe
            $this->command->info('📋 Creating vanilla recipe...');

            $recipe = Recipe::firstOrCreate(
                ['name' => 'Classic Vanilla Ice Cream Recipe'],
                [
                    'product_id' => $vanillaProduct->id,
                    'description' => 'Premium vanilla ice cream - 3000g batch yields 42 scoops',
                    'yield_quantity' => 42, // scoops
                    'instructions' => "1. Mix dry ingredients: FCMP 450g, SKMP 400g, Sugar 1100g, CMC 2g, GMS 36g, Cremofon 6g\n" .
                                     "2. Heat cream (1000g) to 60°C\n" .
                                     "3. Add dry mixture gradually while stirring\n" .
                                     "4. Add water (5ml) and mix well\n" .
                                     "5. Pasteurize at 85°C for 30 seconds\n" .
                                     "6. Cool rapidly to 4°C\n" .
                                     "7. Add vanilla extract (1g)\n" .
                                     "8. Age for 4-24 hours at 4°C\n" .
                                     "9. Churn in ice cream machine\n" .
                                     "10. Harden at -18°C\n" .
                                     "Total batch: 3000g → 42 scoops",
                    'is_active' => true,
                ]
            );

            $this->command->info("  ✓ {$recipe->name}");
            $this->command->info("    Yield: {$recipe->yield_quantity} scoops");
            $this->command->info('');

            // Step 5: Add Recipe Ingredients (Your Formula!)
            $this->command->info('🧪 Adding recipe ingredients...');

            $recipeIngredients = [
                ['sku' => 'FCMP', 'quantity' => 450],
                ['sku' => 'SKMP', 'quantity' => 400],
                ['sku' => 'SUGAR', 'quantity' => 1100],
                ['sku' => 'CMC', 'quantity' => 2],
                ['sku' => 'GMS', 'quantity' => 36],
                ['sku' => 'CREMOFON', 'quantity' => 6],
                ['sku' => 'VANILLA', 'quantity' => 1],
                ['sku' => 'CREAM', 'quantity' => 1000],
                ['sku' => 'WATER', 'quantity' => 5],
            ];

            $totalCost = 0;
            foreach ($recipeIngredients as $ri) {
                $ingredient = $createdIngredients[$ri['sku']];

                RecipeIngredient::firstOrCreate(
                    [
                        'recipe_id' => $recipe->id,
                        'ingredient_id' => $ingredient->id,
                    ],
                    [
                        'quantity_grams' => $ri['quantity'],
                    ]
                );

                $cost = $ingredient->unit_cost * $ri['quantity'];
                $totalCost += $cost;

                $this->command->info(sprintf(
                    "  ✓ %s: %dg × $%.2f = $%.2f",
                    $ingredient->name,
                    $ri['quantity'],
                    $ingredient->unit_cost,
                    $cost
                ));
            }

            $batchSizeGrams = 3000; // Total batch size
            $yieldScoops = $recipe->yield_quantity;

            $costPerScoop = $totalCost / $yieldScoops;
            $retailPerScoop = $vanillaProduct->scoop_price;
            $margin = (($retailPerScoop - $costPerScoop) / $retailPerScoop) * 100;

            $this->command->info('');
            $this->command->info('💰 Cost Analysis:');
            $this->command->info(sprintf("  Total Recipe Cost: $%.2f", $totalCost));
            $this->command->info(sprintf("  Cost Per Scoop: $%.2f", $costPerScoop));
            $this->command->info(sprintf("  Retail Per Scoop: $%.2f", $retailPerScoop));
            $this->command->info(sprintf("  Profit Margin: %.1f%%", $margin));
            $this->command->info('');

            // Step 6: Create Production Batch
            $this->command->info('🏭 Creating production batch...');

            $branch = Branch::first();
            if (!$branch) {
                $branch = Branch::create([
                    'name' => 'Main Store',
                    'slug' => 'main-store',
                    'address' => '123 Main Street',
                    'is_active' => true,
                ]);
                $this->command->info("  ℹ Created branch: {$branch->name}");
            }

            $batchNumber = 'BATCH-' . now()->format('Ymd') . '-VAN-001';

            $batch = ProductionBatch::firstOrCreate(
                ['batch_number' => $batchNumber],
                [
                    'recipe_id' => $recipe->id,
                    'product_id' => $vanillaProduct->id,
                    'branch_id' => $branch->id,
                    'production_date' => now(),
                    'batch_size_grams' => $batchSizeGrams,
                    'total_scoops_produced' => $yieldScoops,
                    'available_scoops' => $yieldScoops,
                    'status' => 'available',
                ]
            );

            $this->command->info("  ✓ Batch Number: {$batch->batch_number}");
            $this->command->info("    Production Date: {$batch->production_date->format('Y-m-d H:i')}");
            $this->command->info("    Branch: {$branch->name}");
            $this->command->info("    Size: {$batch->batch_size_grams}g");
            $this->command->info("    Available: {$batch->available_scoops} scoops");
            $this->command->info('');

            // Summary
            $this->command->info('═══════════════════════════════════════');
            $this->command->info('✅ Vanilla Recipe System Complete!');
            $this->command->info('═══════════════════════════════════════');
            $this->command->info('');
            $this->command->info('Summary:');
            $this->command->info("  • Ingredients: 9 created");
            $this->command->info("  • Product: {$vanillaProduct->name}");
            $this->command->info("  • Recipe: {$recipe->name}");
            $this->command->info("  • Batch: {$batch->batch_number} ({$batch->available_scoops} scoops available)");
            $this->command->info('');
        });
    }
}
