<?php

namespace Database\Seeders;

use App\Models\ExpenseRecord;
use App\Models\Farm;
use App\Models\FeedConfig;
use App\Models\FeedingLog;
use App\Models\HarvestRecord;
use App\Models\InventoryItem;
use App\Models\MortalityLog;
use App\Models\Pond;
use App\Models\ProductionCycle;
use App\Models\SalesRecord;
use App\Models\SamplingRecord;
use App\Models\SpeciesConfig;
use App\Models\StockingRecord;
use App\Models\User;
use App\Models\WaterQualityLog;
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DemoFarmSeeder extends Seeder
{
    public function run(): void
    {
        // 1. Farm
        $farm = Farm::create([
            'name' => 'LucrativeFish Farm',
            'address' => 'Km 5, Ibadan-Lagos Expressway, Ogun State',
            'owner_name' => 'Kolawole Akinsumbo',
            'phone' => '+234 801 234 5678',
            'email' => 'admin@lucratvefish.com',
        ]);

        // 2. Users
        $admin = User::create(['farm_id' => 1, 'name' => 'Kolawole Akinsumbo', 'email' => 'admin@farm.test', 'password' => Hash::make('password'), 'role' => 'admin', 'is_active' => true]);
        $manager = User::create(['farm_id' => 1, 'name' => 'Adebayo Musa', 'email' => 'manager@farm.test', 'password' => Hash::make('password'), 'role' => 'manager', 'is_active' => true]);
        $hand1 = User::create(['farm_id' => 1, 'name' => 'Emeka Okonkwo', 'email' => 'hand1@farm.test', 'password' => Hash::make('password'), 'role' => 'farm_hand', 'is_active' => true]);
        $hand2 = User::create(['farm_id' => 1, 'name' => 'Fatima Yusuf', 'email' => 'hand2@farm.test', 'password' => Hash::make('password'), 'role' => 'farm_hand', 'is_active' => true]);
        $viewer = User::create(['farm_id' => 1, 'name' => 'Investor Bello', 'email' => 'viewer@farm.test', 'password' => Hash::make('password'), 'role' => 'viewer', 'is_active' => true]);

        // 3. Species config
        SpeciesConfig::create(['farm_id' => 1, 'name' => 'Catfish', 'target_weight_g' => 1000, 'safe_ph_min' => 6.5, 'safe_ph_max' => 8.5, 'warning_ph_min' => 6.0, 'warning_ph_max' => 9.0, 'safe_do_min_mgl' => 4.0, 'warning_do_min_mgl' => 2.0, 'safe_temp_min_c' => 25.0, 'safe_temp_max_c' => 30.0, 'safe_ammonia_max_ppm' => 0.05, 'safe_nitrite_max_ppm' => 0.1, 'is_active' => true]);
        SpeciesConfig::create(['farm_id' => 1, 'name' => 'Tilapia', 'target_weight_g' => 600, 'safe_ph_min' => 6.0, 'safe_ph_max' => 9.0, 'warning_ph_min' => 5.5, 'warning_ph_max' => 9.5, 'safe_do_min_mgl' => 3.0, 'warning_do_min_mgl' => 1.5, 'safe_temp_min_c' => 22.0, 'safe_temp_max_c' => 32.0, 'safe_ammonia_max_ppm' => 0.1, 'safe_nitrite_max_ppm' => 0.2, 'is_active' => true]);

        // 4. Feed configs
        FeedConfig::create(['farm_id' => 1, 'brand' => 'Coppens', 'type' => '3mm Floating Pellet', 'size_mm' => 3.0, 'bag_weight_kg' => 15, 'is_active' => true]);
        FeedConfig::create(['farm_id' => 1, 'brand' => 'Coppens', 'type' => '1.5mm Starter Pellet', 'size_mm' => 1.5, 'bag_weight_kg' => 10, 'is_active' => true]);
        FeedConfig::create(['farm_id' => 1, 'brand' => 'Top Feed', 'type' => '4mm Floating Pellet', 'size_mm' => 4.0, 'bag_weight_kg' => 15, 'is_active' => true]);

        // 5. Ponds
        $pond1 = Pond::create(['farm_id' => 1, 'pond_code' => 'POND-001', 'name' => 'Catfish A', 'type' => 'concrete', 'length_m' => 20, 'width_m' => 10, 'depth_m' => 1.5, 'water_source' => 'borehole', 'aeration_type' => '2× paddle aerators', 'location_block' => 'Block A', 'status' => 'active']);
        $pond2 = Pond::create(['farm_id' => 1, 'pond_code' => 'POND-002', 'name' => 'Catfish B', 'type' => 'concrete', 'length_m' => 20, 'width_m' => 10, 'depth_m' => 1.5, 'water_source' => 'borehole', 'aeration_type' => '2× paddle aerators', 'location_block' => 'Block A', 'status' => 'harvest_ready']);
        $pond3 = Pond::create(['farm_id' => 1, 'pond_code' => 'POND-003', 'name' => 'Tilapia A', 'type' => 'earthen', 'length_m' => 30, 'width_m' => 15, 'depth_m' => 1.2, 'water_source' => 'borehole', 'location_block' => 'Block B', 'status' => 'active']);
        $pond4 = Pond::create(['farm_id' => 1, 'pond_code' => 'POND-004', 'name' => 'Catfish C', 'type' => 'tarpaulin', 'length_m' => 5, 'width_m' => 5, 'depth_m' => 1.0, 'water_source' => 'borehole', 'location_block' => 'Block C', 'status' => 'fallow']);

        // 6. Historical closed cycle on Pond 2 (Catfish B — harvest ready after 180 days)
        $closedCycleStart = Carbon::now()->subDays(180);
        $closedCycle = ProductionCycle::create(['farm_id' => 1, 'pond_id' => $pond2->id, 'cycle_number' => 1, 'start_date' => $closedCycleStart->toDateString(), 'end_date' => Carbon::now()->subDays(2)->toDateString(), 'status' => 'closed']);
        StockingRecord::create(['pond_id' => $pond2->id, 'cycle_id' => $closedCycle->id, 'stocking_date' => $closedCycleStart->toDateString(), 'species' => 'Catfish', 'quantity' => 1500, 'avg_weight_g' => 5, 'supplier_name' => 'Ogun Fingerlings Ltd', 'cost_per_fingerling' => 80, 'transport_cost' => 15000, 'logged_by' => $admin->id]);
        $harvest2 = HarvestRecord::create(['farm_id' => 1, 'pond_id' => $pond2->id, 'cycle_id' => $closedCycle->id, 'harvest_date' => Carbon::now()->subDays(2)->toDateString(), 'total_fish_harvested' => 1380, 'total_weight_kg' => 1242, 'total_mortality_count' => 120, 'harvest_type' => 'full_harvest', 'logged_by' => $admin->id]);
        SalesRecord::create(['harvest_id' => $harvest2->id, 'sale_date' => Carbon::now()->subDays(2)->toDateString(), 'buyer_name' => 'Mr. Chukwu Market', 'quantity_kg' => 800, 'price_per_kg_naira' => 1800, 'total_amount_naira' => 1440000, 'payment_method' => 'bank_transfer', 'payment_status' => 'paid', 'amount_received_naira' => 1440000]);
        SalesRecord::create(['harvest_id' => $harvest2->id, 'sale_date' => Carbon::now()->subDays(1)->toDateString(), 'buyer_name' => 'Halima Groceries', 'buyer_contact' => '0812 345 6789', 'quantity_kg' => 442, 'price_per_kg_naira' => 1800, 'total_amount_naira' => 795600, 'payment_method' => 'cash', 'payment_status' => 'partial', 'amount_received_naira' => 400000, 'is_overdue' => false]);

        // 7. Active cycle on Pond 1 (Catfish A — 90 days in)
        $cycle1Start = Carbon::now()->subDays(90);
        $cycle1 = ProductionCycle::create(['farm_id' => 1, 'pond_id' => $pond1->id, 'cycle_number' => 1, 'start_date' => $cycle1Start->toDateString(), 'status' => 'open']);
        StockingRecord::create(['pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'stocking_date' => $cycle1Start->toDateString(), 'species' => 'Catfish', 'quantity' => 2000, 'avg_weight_g' => 5, 'supplier_name' => 'Lagos Fingerlings Co', 'cost_per_fingerling' => 75, 'transport_cost' => 20000, 'logged_by' => $admin->id]);

        // Feeding logs for past 30 days on pond1
        for ($d = 30; $d >= 0; $d--) {
            $date = Carbon::now()->subDays($d)->toDateString();
            foreach (['morning', 'afternoon'] as $time) {
                FeedingLog::create(['pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'feed_date' => $date, 'feed_time' => $time, 'feed_brand' => 'Coppens', 'feed_type' => '3mm Floating Pellet', 'quantity_kg' => rand(8, 12), 'feeding_response' => ['excellent', 'good', 'good', 'good'][array_rand(['excellent', 'good', 'good', 'good'])], 'logged_by' => $hand1->id]);
            }
        }

        // Sampling records
        SamplingRecord::create(['pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'sample_date' => Carbon::now()->subDays(60)->toDateString(), 'fish_sampled_count' => 25, 'total_sample_weight_g' => 3250, 'estimated_live_count' => 1950, 'estimated_biomass_kg' => 253.5, 'target_weight_g' => 1000, 'logged_by' => $admin->id]);
        SamplingRecord::create(['pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'sample_date' => Carbon::now()->subDays(40)->toDateString(), 'fish_sampled_count' => 25, 'total_sample_weight_g' => 6500, 'estimated_live_count' => 1940, 'estimated_biomass_kg' => 504.4, 'target_weight_g' => 1000, 'logged_by' => $admin->id]);
        SamplingRecord::create(['pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'sample_date' => Carbon::now()->subDays(20)->toDateString(), 'fish_sampled_count' => 25, 'total_sample_weight_g' => 12500, 'estimated_live_count' => 1930, 'estimated_biomass_kg' => 965.0, 'target_weight_g' => 1000, 'logged_by' => $admin->id]);

        // Mortality
        MortalityLog::create(['pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'log_date' => Carbon::now()->subDays(70)->toDateString(), 'dead_count' => 30, 'probable_cause' => 'unknown', 'logged_by' => $hand1->id]);
        MortalityLog::create(['pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'log_date' => Carbon::now()->subDays(55)->toDateString(), 'dead_count' => 20, 'probable_cause' => 'water_quality', 'logged_by' => $hand1->id]);

        // Water quality — some alerts
        WaterQualityLog::create(['pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'reading_date' => today()->toDateString(), 'reading_time' => '06:30:00', 'ph' => 7.2, 'dissolved_oxygen_mgl' => 5.8, 'temperature_c' => 27.5, 'logged_by' => $hand2->id]);
        WaterQualityLog::create(['pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'reading_date' => Carbon::yesterday()->toDateString(), 'reading_time' => '06:45:00', 'ph' => 5.8, 'dissolved_oxygen_mgl' => 3.1, 'temperature_c' => 28.0, 'corrective_action' => 'Added 5kg agricultural lime', 'logged_by' => $hand2->id]);

        // Expenses for cycle 1
        ExpenseRecord::create(['farm_id' => 1, 'expense_date' => $cycle1Start->toDateString(), 'category' => 'fingerlings', 'description' => '2000 catfish fingerlings + transport', 'amount_naira' => 170000, 'pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'payment_method' => 'bank_transfer', 'is_auto_generated' => true, 'logged_by' => $admin->id]);
        ExpenseRecord::create(['farm_id' => 1, 'expense_date' => Carbon::now()->subDays(60)->toDateString(), 'category' => 'feed', 'description' => 'Coppens 3mm x 20 bags', 'amount_naira' => 180000, 'pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'payment_method' => 'cash', 'logged_by' => $manager->id]);
        ExpenseRecord::create(['farm_id' => 1, 'expense_date' => Carbon::now()->subDays(30)->toDateString(), 'category' => 'feed', 'description' => 'Coppens 3mm x 20 bags', 'amount_naira' => 190000, 'pond_id' => $pond1->id, 'cycle_id' => $cycle1->id, 'payment_method' => 'cash', 'logged_by' => $manager->id]);
        ExpenseRecord::create(['farm_id' => 1, 'expense_date' => Carbon::now()->subDays(45)->toDateString(), 'category' => 'labour', 'description' => 'Monthly farm hands wages', 'amount_naira' => 120000, 'payment_method' => 'cash', 'logged_by' => $admin->id]);
        ExpenseRecord::create(['farm_id' => 1, 'expense_date' => Carbon::now()->subDays(15)->toDateString(), 'category' => 'electricity', 'description' => 'Generator fuel + PHCN bill', 'amount_naira' => 45000, 'payment_method' => 'cash', 'logged_by' => $admin->id]);

        // 8. Active polyculture cycle on Pond 3 (Tilapia A)
        $cycle3Start = Carbon::now()->subDays(45);
        $cycle3 = ProductionCycle::create(['farm_id' => 1, 'pond_id' => $pond3->id, 'cycle_number' => 1, 'start_date' => $cycle3Start->toDateString(), 'status' => 'open']);
        StockingRecord::create(['pond_id' => $pond3->id, 'cycle_id' => $cycle3->id, 'stocking_date' => $cycle3Start->toDateString(), 'species' => 'Tilapia', 'quantity' => 3000, 'avg_weight_g' => 3, 'supplier_name' => 'Oyo Fish Farm', 'cost_per_fingerling' => 50, 'transport_cost' => 10000, 'logged_by' => $admin->id]);
        StockingRecord::create(['pond_id' => $pond3->id, 'cycle_id' => $cycle3->id, 'stocking_date' => $cycle3Start->toDateString(), 'species' => 'Catfish', 'quantity' => 500, 'avg_weight_g' => 8, 'supplier_name' => 'Oyo Fish Farm', 'cost_per_fingerling' => 80, 'transport_cost' => 0, 'logged_by' => $admin->id]);
        // Brief feeding history
        for ($d = 10; $d >= 0; $d--) {
            FeedingLog::create(['pond_id' => $pond3->id, 'cycle_id' => $cycle3->id, 'feed_date' => Carbon::now()->subDays($d)->toDateString(), 'feed_time' => 'morning', 'feed_brand' => 'Top Feed', 'feed_type' => '4mm Floating Pellet', 'quantity_kg' => rand(15, 20), 'feeding_response' => 'good', 'logged_by' => $hand2->id]);
        }
        WaterQualityLog::create(['pond_id' => $pond3->id, 'cycle_id' => $cycle3->id, 'reading_date' => today()->toDateString(), 'reading_time' => '07:00:00', 'ph' => 7.5, 'dissolved_oxygen_mgl' => 6.2, 'temperature_c' => 28.0, 'logged_by' => $hand2->id]);

        // 9. Inventory (2 below reorder)
        InventoryItem::create(['farm_id' => 1, 'item_name' => 'Coppens 3mm Floating Pellet', 'category' => 'feed', 'unit' => 'kg', 'current_stock' => 150, 'reorder_threshold' => 200, 'unit_cost_naira' => 9000, 'supplier_name' => 'Coppens Nigeria']);
        InventoryItem::create(['farm_id' => 1, 'item_name' => 'Coppens 1.5mm Starter', 'category' => 'feed', 'unit' => 'kg', 'current_stock' => 500, 'reorder_threshold' => 100, 'unit_cost_naira' => 11000, 'supplier_name' => 'Coppens Nigeria']);
        InventoryItem::create(['farm_id' => 1, 'item_name' => 'Top Feed 4mm', 'category' => 'feed', 'unit' => 'kg', 'current_stock' => 40, 'reorder_threshold' => 100, 'unit_cost_naira' => 8500, 'supplier_name' => 'Top Feed Ltd']);
        InventoryItem::create(['farm_id' => 1, 'item_name' => 'Agricultural Lime', 'category' => 'chemical', 'unit' => 'kg', 'current_stock' => 80, 'reorder_threshold' => 50, 'unit_cost_naira' => 500]);
        InventoryItem::create(['farm_id' => 1, 'item_name' => 'Potassium Permanganate', 'category' => 'drug', 'unit' => 'kg', 'current_stock' => 0.5, 'reorder_threshold' => 2, 'unit_cost_naira' => 8000]);

        $this->command->info('Demo farm seeded successfully!');
        $this->command->info('Login: admin@farm.test / password');
    }
}
