<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Harvest;
use App\Models\PlannedTask;
use App\Models\VarietyVariation;
use App\Models\VineyardRow;

class HarvestSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $rows = VineyardRow::with('varietyVariation.grapeVariety')
            ->get()
            ->groupBy(fn (VineyardRow $row) => $row->varietyVariation->grapeVariety->variety_name ?? $row->id);

        $variations = VarietyVariation::with('grapeVariety')
            ->get()
            ->keyBy(fn (VarietyVariation $variation) => ($variation->grapeVariety->variety_name ?? $variation->id) . ':' . $variation->color);

        $harvests = [
            // Historical harvests from 2024
            [
                'variety' => 'Grüner Veltliner',
                'color' => 'green',
                'weight' => 850.50,
                'sugar_content' => 19.5,
                'date' => '2024-09-15',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Excellent harvest, optimal ripeness',
                'weather_conditions' => 'Sunny, 22°C',
                'harvest_time' => '08:00:00',
                'executed_at' => '2024-09-15',
            ],
            [
                'variety' => 'Riesling',
                'color' => 'green',
                'weight' => 720.30,
                'sugar_content' => 21.2,
                'date' => '2024-09-20',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Premium quality, high sugar content',
                'weather_conditions' => 'Partly cloudy, 20°C',
                'harvest_time' => '07:30:00',
                'executed_at' => '2024-09-20',
            ],
            [
                'variety' => 'Blaufränkisch',
                'color' => 'blue',
                'weight' => 950.00,
                'sugar_content' => 22.8,
                'date' => '2024-10-05',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Best harvest of the season, ideal conditions',
                'weather_conditions' => 'Sunny, 18°C',
                'harvest_time' => '09:00:00',
                'executed_at' => '2024-10-05',
            ],
            [
                'variety' => 'St. Laurent',
                'color' => 'blue',
                'weight' => 600.75,
                'sugar_content' => 20.5,
                'date' => '2024-10-01',
                'quality' => 'good',
                'grape_condition' => 'healthy',
                'notes' => 'Good quality, smaller yield',
                'weather_conditions' => 'Overcast, 16°C',
                'harvest_time' => '10:00:00',
                'planned_for' => '2025-09-22',
            ],
            [
                'variety' => 'Müller Thurgau',
                'color' => 'green',
                'weight' => 780.20,
                'sugar_content' => 18.3,
                'date' => '2024-09-10',
                'quality' => 'good',
                'grape_condition' => 'healthy',
                'notes' => 'Early harvest, lighter wine',
                'weather_conditions' => 'Sunny, 24°C',
                'harvest_time' => '08:30:00',
                'planned_for' => '2025-09-12',
            ],

            // ========== HISTORICAL HARVESTS 2023 ==========
            [
                'variety' => 'Grüner Veltliner',
                'color' => 'green',
                'weight' => 920.00,
                'sugar_content' => 19.2,
                'date' => '2023-09-18',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Main harvest for Cabinet wine, excellent quality',
                'weather_conditions' => 'Sunny, 21°C',
                'harvest_time' => '08:00:00',
                'executed_at' => '2023-09-18',
            ],
            [
                'variety' => 'Grüner Veltliner',
                'color' => 'green',
                'weight' => 650.50,
                'sugar_content' => 21.8,
                'date' => '2023-10-12',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Late harvest, higher sugar for semi-dry wine',
                'weather_conditions' => 'Partly cloudy, 18°C',
                'harvest_time' => '09:00:00',
                'executed_at' => '2023-10-12',
            ],
            [
                'variety' => 'Müller Thurgau',
                'color' => 'green',
                'weight' => 890.75,
                'sugar_content' => 17.8,
                'date' => '2023-09-08',
                'quality' => 'good',
                'grape_condition' => 'healthy',
                'notes' => 'Early harvest, aromatic profile',
                'weather_conditions' => 'Sunny, 23°C',
                'harvest_time' => '07:30:00',
                'executed_at' => '2023-09-08',
            ],
            [
                'variety' => 'Chardonnay',
                'color' => 'green',
                'weight' => 580.30,
                'sugar_content' => 20.5,
                'date' => '2023-09-22',
                'quality' => 'good',
                'grape_condition' => 'healthy',
                'notes' => 'Balanced harvest for unfiltered wine',
                'weather_conditions' => 'Sunny, 20°C',
                'harvest_time' => '08:00:00',
                'executed_at' => '2023-09-22',
            ],
            [
                'variety' => 'Blaufränkisch',
                'color' => 'blue',
                'weight' => 1050.00,
                'sugar_content' => 22.0,
                'date' => '2023-10-08',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Premium quality for classic red wine',
                'weather_conditions' => 'Sunny, 17°C',
                'harvest_time' => '09:30:00',
                'executed_at' => '2023-10-08',
            ],
            [
                'variety' => 'St. Laurent',
                'color' => 'blue',
                'weight' => 720.50,
                'sugar_content' => 20.8,
                'date' => '2023-10-02',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Main harvest for Moravian style',
                'weather_conditions' => 'Partly cloudy, 16°C',
                'harvest_time' => '08:30:00',
                'executed_at' => '2023-10-02',
            ],
            [
                'variety' => 'St. Laurent',
                'color' => 'blue',
                'weight' => 480.25,
                'sugar_content' => 19.5,
                'date' => '2023-09-28',
                'quality' => 'good',
                'grape_condition' => 'healthy',
                'notes' => 'Early harvest for lighter rosé style',
                'weather_conditions' => 'Sunny, 19°C',
                'harvest_time' => '07:00:00',
                'executed_at' => '2023-09-28',
            ],

            // ========== HISTORICAL HARVESTS 2022 ==========
            [
                'variety' => 'Grüner Veltliner',
                'color' => 'green',
                'weight' => 580.80,
                'sugar_content' => 22.5,
                'date' => '2022-10-20',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Selection harvest, hand-picked clusters for premium wine',
                'weather_conditions' => 'Cool, 14°C',
                'harvest_time' => '10:00:00',
                'executed_at' => '2022-10-20',
            ],
            [
                'variety' => 'Riesling',
                'color' => 'green',
                'weight' => 640.60,
                'sugar_content' => 20.8,
                'date' => '2022-10-05',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Classic dry Riesling harvest, perfect acidity',
                'weather_conditions' => 'Sunny, 18°C',
                'harvest_time' => '08:00:00',
                'executed_at' => '2022-10-05',
            ],
            [
                'variety' => 'Chardonnay',
                'color' => 'green',
                'weight' => 510.40,
                'sugar_content' => 21.5,
                'date' => '2022-09-25',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Premium grapes for barrel aging',
                'weather_conditions' => 'Sunny, 21°C',
                'harvest_time' => '08:30:00',
                'executed_at' => '2022-09-25',
            ],
            [
                'variety' => 'Blaufränkisch',
                'color' => 'blue',
                'weight' => 680.75,
                'sugar_content' => 23.2,
                'date' => '2022-10-12',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Reserve selection, concentrated flavors',
                'weather_conditions' => 'Sunny, 16°C',
                'harvest_time' => '09:00:00',
                'executed_at' => '2022-10-12',
            ],
            [
                'variety' => 'St. Laurent',
                'color' => 'blue',
                'weight' => 620.90,
                'sugar_content' => 21.8,
                'date' => '2022-10-05',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Premium harvest for barrel aging',
                'weather_conditions' => 'Partly cloudy, 17°C',
                'harvest_time' => '08:00:00',
                'executed_at' => '2022-10-05',
            ],

            // ========== HISTORICAL HARVESTS 2021 ==========
            [
                'variety' => 'Riesling',
                'color' => 'green',
                'weight' => 420.50,
                'sugar_content' => 28.5,
                'date' => '2021-11-08',
                'quality' => 'excellent',
                'grape_condition' => 'botrytis-affected',
                'notes' => 'Noble rot berries, individual selection for sweet wine',
                'weather_conditions' => 'Foggy morning, 10°C',
                'harvest_time' => '10:00:00',
                'executed_at' => '2021-11-08',
            ],

            // ========== HISTORICAL HARVESTS 2020 ==========
            [
                'variety' => 'Blaufränkisch',
                'color' => 'blue',
                'weight' => 550.00,
                'sugar_content' => 23.8,
                'date' => '2020-10-18',
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Exceptional vintage, archive quality',
                'weather_conditions' => 'Perfect harvest weather, 15°C',
                'harvest_time' => '09:00:00',
                'executed_at' => '2020-10-18',
            ],

            // Recent harvests (within last 30 days) - dynamic dates
            [
                'variety' => 'Chardonnay',
                'color' => 'green',
                'weight' => 420.50,
                'sugar_content' => 20.8,
                'date' => now()->subDays(5)->format('Y-m-d'),
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'First Chardonnay harvest - excellent for sparkling wine',
                'weather_conditions' => 'Sunny, 19°C',
                'harvest_time' => '07:00:00',
            ],
            [
                'variety' => 'Grüner Veltliner',
                'color' => 'green',
                'weight' => 320.75,
                'sugar_content' => 19.2,
                'date' => now()->subDays(12)->format('Y-m-d'),
                'quality' => 'good',
                'grape_condition' => 'healthy',
                'notes' => 'Partial harvest from north section',
                'weather_conditions' => 'Partly cloudy, 17°C',
                'harvest_time' => '08:30:00',
            ],
            [
                'variety' => 'Riesling',
                'color' => 'green',
                'weight' => 280.40,
                'sugar_content' => 22.5,
                'date' => now()->subDays(18)->format('Y-m-d'),
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Late harvest - high sugar content for dessert wine',
                'weather_conditions' => 'Cool, 12°C',
                'harvest_time' => '09:00:00',
            ],
            [
                'variety' => 'Blaufränkisch',
                'color' => 'blue',
                'weight' => 450.00,
                'sugar_content' => 21.5,
                'date' => now()->subDays(8)->format('Y-m-d'),
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Premium selection for reserve wine',
                'weather_conditions' => 'Sunny, 16°C',
                'harvest_time' => '08:00:00',
            ],

            // ========== FULLY AVAILABLE HARVESTS (Not yet used in production) ==========
            [
                'variety' => 'Grüner Veltliner',
                'color' => 'green',
                'weight' => 780.40,
                'sugar_content' => 19.8,
                'date' => now()->subDays(3)->format('Y-m-d'),
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Fresh harvest, excellent for young wine production',
                'weather_conditions' => 'Sunny, 20°C',
                'harvest_time' => '07:30:00',
            ],
            [
                'variety' => 'Müller Thurgau',
                'color' => 'green',
                'weight' => 650.25,
                'sugar_content' => 18.0,
                'date' => now()->subDays(6)->format('Y-m-d'),
                'quality' => 'good',
                'grape_condition' => 'healthy',
                'notes' => 'Aromatic harvest, ready for processing',
                'weather_conditions' => 'Partly cloudy, 19°C',
                'harvest_time' => '08:00:00',
            ],
            [
                'variety' => 'Chardonnay',
                'color' => 'green',
                'weight' => 540.80,
                'sugar_content' => 21.0,
                'date' => now()->subDays(2)->format('Y-m-d'),
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Premium quality, suitable for barrel aging',
                'weather_conditions' => 'Sunny, 21°C',
                'harvest_time' => '07:00:00',
            ],
            [
                'variety' => 'Riesling',
                'color' => 'green',
                'weight' => 470.60,
                'sugar_content' => 20.5,
                'date' => now()->subDays(10)->format('Y-m-d'),
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Balanced acidity, perfect for classic dry style',
                'weather_conditions' => 'Cool, 15°C',
                'harvest_time' => '08:30:00',
            ],
            [
                'variety' => 'St. Laurent',
                'color' => 'blue',
                'weight' => 690.50,
                'sugar_content' => 20.2,
                'date' => now()->subDays(4)->format('Y-m-d'),
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Excellent color and tannins, available for production',
                'weather_conditions' => 'Partly cloudy, 17°C',
                'harvest_time' => '09:00:00',
            ],
            [
                'variety' => 'Blaufränkisch',
                'color' => 'blue',
                'weight' => 820.00,
                'sugar_content' => 22.5,
                'date' => now()->subDays(7)->format('Y-m-d'),
                'quality' => 'excellent',
                'grape_condition' => 'healthy',
                'notes' => 'Rich concentration, ideal for reserve wine',
                'weather_conditions' => 'Sunny, 18°C',
                'harvest_time' => '08:30:00',
            ],
            [
                'variety' => 'Grüner Veltliner',
                'color' => 'green',
                'weight' => 560.30,
                'sugar_content' => 18.5,
                'date' => '2023-09-25',
                'quality' => 'good',
                'grape_condition' => 'healthy',
                'notes' => 'Secondary harvest from 2023, still available',
                'weather_conditions' => 'Overcast, 18°C',
                'harvest_time' => '09:30:00',
                'executed_at' => '2023-09-25',
            ],
            [
                'variety' => 'Chardonnay',
                'color' => 'green',
                'weight' => 390.75,
                'sugar_content' => 19.8,
                'date' => '2023-10-05',
                'quality' => 'good',
                'grape_condition' => 'healthy',
                'notes' => 'Late 2023 harvest, clean and fresh',
                'weather_conditions' => 'Sunny, 16°C',
                'harvest_time' => '08:00:00',
                'executed_at' => '2023-10-05',
            ],
            [
                'variety' => 'St. Laurent',
                'color' => 'blue',
                'weight' => 410.20,
                'sugar_content' => 19.0,
                'date' => '2022-09-28',
                'quality' => 'good',
                'grape_condition' => 'healthy',
                'notes' => 'Older harvest from 2022, still usable for blending',
                'weather_conditions' => 'Partly cloudy, 19°C',
                'harvest_time' => '10:00:00',
                'executed_at' => '2022-09-28',
            ],
            [
                'variety' => 'Müller Thurgau',
                'color' => 'green',
                'weight' => 720.50,
                'sugar_content' => 17.5,
                'date' => '2022-09-15',
                'quality' => 'good',
                'grape_condition' => 'healthy',
                'notes' => '2022 reserve harvest, light and aromatic',
                'weather_conditions' => 'Sunny, 22°C',
                'harvest_time' => '07:30:00',
                'executed_at' => '2022-09-15',
            ],

            // ========== PLANNED HARVESTS (Future - No completion data) ==========
            // Note: These have minimal data since they're planned, not yet executed
            [
                'variety' => 'Grüner Veltliner',
                'color' => 'green',
                'weight' => 0,  // Placeholder - actual weight unknown until harvest
                'date' => now()->addYear()->addMonths(8)->format('Y-m-d'), // ~Sept 2026
                'notes' => 'Planned harvest for premium wine production',
                'planned_for' => now()->addYear()->addMonths(8)->format('Y-m-d'),
            ],
            [
                'variety' => 'Riesling',
                'color' => 'green',
                'weight' => 0,
                'date' => now()->addYear()->addMonths(8)->addDays(10)->format('Y-m-d'), // ~Sept 2026
                'notes' => 'Expected high sugar content for late harvest wine',
                'planned_for' => now()->addYear()->addMonths(8)->addDays(10)->format('Y-m-d'),
            ],
            [
                'variety' => 'Chardonnay',
                'color' => 'green',
                'weight' => 0,
                'date' => now()->addYear()->addMonths(9)->format('Y-m-d'), // ~Oct 2026
                'notes' => 'Planned harvest for reserve Chardonnay',
                'planned_for' => now()->addYear()->addMonths(9)->format('Y-m-d'),
            ],
            [
                'variety' => 'Blaufränkisch',
                'color' => 'blue',
                'weight' => 0,
                'date' => now()->addYear()->addMonths(9)->addDays(5)->format('Y-m-d'), // ~Oct 2026
                'notes' => 'Planned red grape harvest for full-bodied wine',
                'planned_for' => now()->addYear()->addMonths(9)->addDays(5)->format('Y-m-d'),
            ],
            [
                'variety' => 'St. Laurent',
                'color' => 'blue',
                'weight' => 0,
                'date' => now()->addYear()->addMonths(9)->addWeeks(1)->format('Y-m-d'), // ~Oct 2026
                'notes' => 'Planned harvest for elegant red wine',
                'planned_for' => now()->addYear()->addMonths(9)->addWeeks(1)->format('Y-m-d'),
            ],
        ];

        // Track which rows have been used for which years
        $rowYearUsage = [];

        foreach ($harvests as $harvest) {
            $varietyRows = $rows[$harvest['variety']] ?? collect();
            $variationKey = $harvest['variety'] . ':' . $harvest['color'];
            $variation = $variations[$variationKey] ?? null;

            // Resolve a usable variety variation id; fall back to row assignment or any variation for the variety
            $variationId = $variation?->id;
            if (! $variationId && $varietyRows->isNotEmpty()) {
                $variationId = $varietyRows->first()->variety_variation_id;
            }
            if (! $variationId) {
                $variationId = \App\Models\VarietyVariation::whereHas(
                    'grapeVariety',
                    fn ($q) => $q->where('variety_name', $harvest['variety'])
                )->value('id');
            }

            if ($varietyRows->isEmpty() || ! $variationId) {
                continue;
            }

            // Get the year from the PLANNED date (not harvest date)
            // Planned date is: planned_for > executed_at > date
            $plannedDateField = $harvest['planned_for'] ?? $harvest['executed_at'] ?? $harvest['date'];
            $plannedYear = is_string($plannedDateField)
                ? \Carbon\Carbon::parse($plannedDateField)->year
                : now()->subDays((int)$plannedDateField)->year;

            // Find a row that hasn't been used for this planned year
            $row = null;
            foreach ($varietyRows as $candidateRow) {
                $rowYearKey = $candidateRow->id . '_' . $plannedYear;
                if (!isset($rowYearUsage[$rowYearKey])) {
                    $row = $candidateRow;
                    $rowYearUsage[$rowYearKey] = true;
                    break;
                }
            }

            // If all rows for this variety already have a harvest this planned year, skip
            if (!$row) {
                continue;
            }

            $harvestModel = Harvest::updateOrCreate(
                [
                    'vineyard_row_id' => $row->id,
                    'date' => $harvest['date'],
                ],
                [
                    'variety_variation_id' => $variationId,
                    'weight' => $harvest['weight'] ?? null,
                    'sugar_content' => $harvest['sugar_content'] ?? null,
                    'quality' => $harvest['quality'] ?? null,
                    'grape_condition' => $harvest['grape_condition'] ?? null,
                    'notes' => $harvest['notes'] ?? null,
                    'weather_conditions' => $harvest['weather_conditions'] ?? null,
                    'harvest_time' => $harvest['harvest_time'] ?? null,
                ]
            );

            $plannedDate = $harvest['planned_for'] ?? null;
            $executionDate = $harvest['executed_at'] ?? null;

            // If harvest has completion data (sugar, weather, etc.), it's completed
            // Set execution_date to the harvest date, regardless of 'planned_for'
            $hasCompletionData = $harvestModel->sugar_content || $harvestModel->weather_conditions || $harvestModel->quality_rating;
            if ($hasCompletionData && !$executionDate) {
                $executionDate = $harvestModel->date?->format('Y-m-d');
            }

            $defaultDate = $executionDate ?? $harvestModel->date?->format('Y-m-d');

            if ($plannedDate || $executionDate || $defaultDate) {
                PlannedTask::updateOrCreate(
                    [
                        'type' => 'Harvest',
                        'taskable_id' => $harvestModel->getKey(),
                        'taskable_type' => Harvest::class,
                    ],
                    [
                        'planned_date' => $plannedDate ?? $defaultDate,
                        'execution_date' => $executionDate,
                        'note' => $harvest['notes'],
                    ]
                );
            }
        }

        if ($this->command) {
            $this->command->info('✓ Created ' . count($harvests) . ' harvests');
        }
    }
}
