<?php

namespace Database\Seeders;

use App\Models\City;
use App\Models\FeasibilityReport;
use App\Models\State;
use App\Models\User;
use App\Models\Zone;
use App\Models\ZoneRule;
use Illuminate\Database\Seeder;

/**
 * Seeds sample feasibility reports for testing / demo purposes.
 * Depends on: AdminSeeder, IndiaStatesSeeder, MaharashtraDataSeeder.
 */
class FeasibilityReportSeeder extends Seeder
{
    public function run(): void
    {
        $user = User::where('email', 'admin@landfeasibility.com')->first();
        if (! $user) {
            $this->command->warn('Admin user not found. Run AdminSeeder first.');
            return;
        }

        $mh     = State::where('code', 'MH')->first();
        $mumbai = City::where('code', 'MUM')->first();
        $pune   = City::where('code', 'PUN')->first();

        if (! $mh || ! $mumbai) {
            $this->command->warn('Maharashtra data not found. Run MaharashtraDataSeeder first.');
            return;
        }

        $zoneR1  = Zone::where('name', 'R1 — Residential (Low Density)')->first();
        $zoneR2  = Zone::where('name', 'R2 — Residential (Medium Density)')->first();
        $zoneC1  = Zone::where('name', 'C1 — Commercial (Neighbourhood)')->first();
        $zoneC2  = Zone::where('name', 'C2 — Commercial (District Level)')->first();
        $zoneMix = Zone::where('name', 'MIX — Mixed Use')->first();

        // Pick representative zone rules (12 m road slab for most)
        $ruleR1  = $zoneR1  ? ZoneRule::where('zone_id', $zoneR1->id)->where('road_width_min_m', 12)->first()
                                      ?? ZoneRule::where('zone_id', $zoneR1->id)->first()  : null;
        $ruleR2  = $zoneR2  ? ZoneRule::where('zone_id', $zoneR2->id)->where('road_width_min_m', 12)->first()
                                      ?? ZoneRule::where('zone_id', $zoneR2->id)->first()  : null;
        $ruleC1  = $zoneC1  ? ZoneRule::where('zone_id', $zoneC1->id)->where('road_width_min_m', 12)->first()
                                      ?? ZoneRule::where('zone_id', $zoneC1->id)->first()  : null;
        $ruleC2  = $zoneC2  ? ZoneRule::where('zone_id', $zoneC2->id)->where('road_width_min_m', 18)->first()
                                      ?? ZoneRule::where('zone_id', $zoneC2->id)->first()  : null;
        $ruleMix = $zoneMix ? ZoneRule::where('zone_id', $zoneMix->id)->where('road_width_min_m', 12)->first()
                                      ?? ZoneRule::where('zone_id', $zoneMix->id)->first() : null;

        $reports = [

            // ── 1. Completed — R2 Residential, Mumbai, good score ──────────────
            [
                'user_id'              => $user->id,
                'state_id'             => $mh->id,
                'city_id'              => $mumbai->id,
                'zone_id'              => $zoneR2?->id,
                'zone_rule_id'         => $ruleR2?->id,
                'address'              => '14, Linking Road, Bandra West, Mumbai, Maharashtra 400050',
                'latitude'             => 19.0596,
                'longitude'            => 72.8295,
                'plot_area_sqm'        => 500.0,
                'road_width_m'         => 12.0,
                'project_type'         => 'residential',
                'max_buildable_area_sqm' => 1250.0,
                'ground_coverage_sqm'  => 225.0,
                'max_floors'           => 6,
                'feasibility_score'    => 78,
                'status'               => 'completed',
                'setback_summary'      => ['front_m' => 4.5, 'side_m' => 2.0, 'rear_m' => 3.0, 'note' => 'DCPR 2034 Reg.31'],
                'restriction_flags'    => ['coastal_zone' => false, 'heritage_zone' => false, 'flood_zone' => false, 'aarey_buffer' => false],
                'permitted_uses'       => ['Residential', 'Schools', 'Clinics', 'Offices (Ground Floor)'],
                'cost_estimates'       => [
                    'construction_cost_min_inr'    => 18750000,
                    'construction_cost_max_inr'    => 25000000,
                    'gross_development_value_inr'  => 62500000,
                    'estimated_profit_inr'         => 40625000,
                    'roi_pct'                      => 186,
                    'monthly_rent_estimate_inr'    => 375000,
                    'annual_rent_estimate_inr'     => 4500000,
                    'breakeven_years'              => 5,
                    'construction_rate_min_sqm'    => 15000,
                    'construction_rate_max_sqm'    => 20000,
                    'note'                         => 'Estimates based on Bandra West prevailing rates (2025-26).',
                ],
                'result_data'          => [
                    'summary'  => 'Plot is well-suited for a mid-rise residential building under R2 zoning.',
                    'ai_notes' => 'Proximity to Linking Road metro station adds ~15% valuation premium.',
                ],
                'calculation_log'      => [
                    ['step' => 'Zone Detection',    'result' => 'R2 — Residential (Medium Density)'],
                    ['step' => 'FSI Applied',        'result' => '2.5 (12 m road band)'],
                    ['step' => 'Ground Coverage',   'result' => '45% → 225 sqm'],
                    ['step' => 'Max BUA',            'result' => '500 × 2.5 = 1,250 sqm'],
                    ['step' => 'Floors',             'result' => 'floor(1250 / 225) = 5 → +1 stilt = 6'],
                ],
            ],

            // ── 2. Completed — C1 Commercial, Mumbai, medium score ─────────────
            [
                'user_id'              => $user->id,
                'state_id'             => $mh->id,
                'city_id'              => $mumbai->id,
                'zone_id'              => $zoneC1?->id,
                'zone_rule_id'         => $ruleC1?->id,
                'address'              => '301, SV Road, Andheri West, Mumbai, Maharashtra 400058',
                'latitude'             => 19.1196,
                'longitude'            => 72.8353,
                'plot_area_sqm'        => 300.0,
                'road_width_m'         => 15.0,
                'project_type'         => 'commercial',
                'max_buildable_area_sqm' => 750.0,
                'ground_coverage_sqm'  => 150.0,
                'max_floors'           => 5,
                'feasibility_score'    => 62,
                'status'               => 'completed',
                'setback_summary'      => ['front_m' => 4.5, 'side_m' => 2.5, 'rear_m' => 3.0, 'note' => 'DCPR 2034 Reg.32'],
                'restriction_flags'    => ['coastal_zone' => false, 'heritage_zone' => false, 'flood_zone' => false, 'narrow_road' => false],
                'permitted_uses'       => ['Retail', 'Offices', 'Restaurants', 'Banks', 'Hotels'],
                'cost_estimates'       => [
                    'construction_cost_min_inr'    => 18750000,
                    'construction_cost_max_inr'    => 26250000,
                    'gross_development_value_inr'  => 56250000,
                    'estimated_profit_inr'         => 33750000,
                    'roi_pct'                      => 148,
                    'monthly_rent_estimate_inr'    => 525000,
                    'annual_rent_estimate_inr'     => 6300000,
                    'breakeven_years'              => 4,
                    'construction_rate_min_sqm'    => 25000,
                    'construction_rate_max_sqm'    => 35000,
                    'note'                         => 'Commercial rates in Andheri West (2025-26).',
                ],
                'result_data'          => [
                    'summary'  => 'Marginal feasibility — plot size limits scale but location has strong commercial demand.',
                    'ai_notes' => 'SV Road catchment suitable for neighbourhood retail or professional offices.',
                ],
                'calculation_log'      => [
                    ['step' => 'Zone Detection', 'result' => 'C1 — Commercial (Neighbourhood)'],
                    ['step' => 'FSI Applied',     'result' => '2.5 (12-18 m road band)'],
                    ['step' => 'Max BUA',         'result' => '300 × 2.5 = 750 sqm'],
                    ['step' => 'Ground Coverage', 'result' => '50% → 150 sqm'],
                    ['step' => 'Floors',          'result' => '5'],
                ],
            ],

            // ── 3. Completed — Mixed Use, Pune, high score ─────────────────────
            [
                'user_id'              => $user->id,
                'state_id'             => $mh->id,
                'city_id'              => $pune?->id,
                'zone_id'              => $zoneMix?->id,
                'zone_rule_id'         => $ruleMix?->id,
                'address'              => '55, Baner Road, Baner, Pune, Maharashtra 411045',
                'latitude'             => 18.5590,
                'longitude'            => 73.7868,
                'plot_area_sqm'        => 1200.0,
                'road_width_m'         => 18.0,
                'project_type'         => 'mixed',
                'max_buildable_area_sqm' => 3000.0,
                'ground_coverage_sqm'  => 600.0,
                'max_floors'           => 8,
                'feasibility_score'    => 85,
                'status'               => 'completed',
                'setback_summary'      => ['front_m' => 4.5, 'side_m' => 2.5, 'rear_m' => 3.0, 'note' => 'DCPR 2034 Reg.35'],
                'restriction_flags'    => ['coastal_zone' => false, 'heritage_zone' => false, 'flood_zone' => false],
                'permitted_uses'       => ['Residential', 'Retail (Ground)', 'Offices', 'Hotels', 'Service Apartments'],
                'cost_estimates'       => [
                    'construction_cost_min_inr'    => 54000000,
                    'construction_cost_max_inr'    => 72000000,
                    'gross_development_value_inr'  => 210000000,
                    'estimated_profit_inr'         => 147000000,
                    'roi_pct'                      => 232,
                    'monthly_rent_estimate_inr'    => 1500000,
                    'annual_rent_estimate_inr'     => 18000000,
                    'breakeven_years'              => 4,
                    'construction_rate_min_sqm'    => 18000,
                    'construction_rate_max_sqm'    => 24000,
                    'note'                         => 'Baner is an IT corridor; premium mixed-use demand is high.',
                ],
                'result_data'          => [
                    'summary'  => 'Excellent feasibility. Large plot on 18 m road in IT corridor with mixed-use zoning.',
                    'ai_notes' => 'Ground + 2 floors retail, upper floors residential / serviced apartments recommended.',
                ],
                'calculation_log'      => [
                    ['step' => 'Zone Detection', 'result' => 'MIX — Mixed Use'],
                    ['step' => 'FSI Applied',     'result' => '2.5 (12-18 m road band)'],
                    ['step' => 'Max BUA',         'result' => '1200 × 2.5 = 3,000 sqm'],
                    ['step' => 'Ground Coverage', 'result' => '50% → 600 sqm'],
                    ['step' => 'Floors',          'result' => '8'],
                ],
            ],

            // ── 4. Completed — R1 Residential, small plot, low score ──────────
            [
                'user_id'              => $user->id,
                'state_id'             => $mh->id,
                'city_id'              => $mumbai->id,
                'zone_id'              => $zoneR1?->id,
                'zone_rule_id'         => $ruleR1?->id,
                'address'              => '7, Gokhale Road, Dadar West, Mumbai, Maharashtra 400028',
                'latitude'             => 19.0176,
                'longitude'            => 72.8426,
                'plot_area_sqm'        => 80.0,
                'road_width_m'         => 9.0,
                'project_type'         => 'residential',
                'max_buildable_area_sqm' => 80.0,
                'ground_coverage_sqm'  => 40.0,
                'max_floors'           => 2,
                'feasibility_score'    => 34,
                'status'               => 'completed',
                'setback_summary'      => ['front_m' => 3.0, 'side_m' => 1.5, 'rear_m' => 3.0, 'note' => 'DCPR 2034 Reg.30'],
                'restriction_flags'    => ['coastal_zone' => false, 'heritage_zone' => true, 'flood_zone' => false, 'minimum_plot_size' => true],
                'permitted_uses'       => ['Residential Dwellings', 'Clinics', 'Places of Worship'],
                'cost_estimates'       => [
                    'construction_cost_min_inr'    => 1200000,
                    'construction_cost_max_inr'    => 1600000,
                    'gross_development_value_inr'  => 4800000,
                    'estimated_profit_inr'         => 3400000,
                    'roi_pct'                      => 239,
                    'monthly_rent_estimate_inr'    => 28000,
                    'annual_rent_estimate_inr'     => 336000,
                    'breakeven_years'              => 4,
                    'construction_rate_min_sqm'    => 15000,
                    'construction_rate_max_sqm'    => 20000,
                    'note'                         => 'Small plot; redevelopment ROI is high but absolute returns limited.',
                ],
                'result_data'          => [
                    'summary'  => 'Challenging feasibility. Heritage overlay and minimum plot size restrictions apply.',
                    'ai_notes' => 'Heritage plot — any demolition requires heritage committee NOC. Consider renovation instead.',
                ],
                'calculation_log'      => [
                    ['step' => 'Zone Detection',    'result' => 'R1 — Residential (Low Density)'],
                    ['step' => 'Heritage Flag',      'result' => 'Grade II Heritage — Additional clearance needed'],
                    ['step' => 'FSI Applied',        'result' => '1.0 (9 m road band)'],
                    ['step' => 'Max BUA',            'result' => '80 × 1.0 = 80 sqm'],
                    ['step' => 'Ground Coverage',   'result' => '50% → 40 sqm'],
                    ['step' => 'Floors',             'result' => '2'],
                ],
            ],

            // ── 5. Completed — C2 Commercial, Mumbai, high score ──────────────
            [
                'user_id'              => $user->id,
                'state_id'             => $mh->id,
                'city_id'              => $mumbai->id,
                'zone_id'              => $zoneC2?->id,
                'zone_rule_id'         => $ruleC2?->id,
                'address'              => '1502, BKC, Bandra Kurla Complex, Mumbai, Maharashtra 400051',
                'latitude'             => 19.0659,
                'longitude'            => 72.8693,
                'plot_area_sqm'        => 2000.0,
                'road_width_m'         => 24.0,
                'project_type'         => 'commercial',
                'max_buildable_area_sqm' => 6000.0,
                'ground_coverage_sqm'  => 1100.0,
                'max_floors'           => 14,
                'feasibility_score'    => 91,
                'status'               => 'completed',
                'setback_summary'      => ['front_m' => 6.0, 'side_m' => 3.0, 'rear_m' => 4.5, 'note' => 'DCPR 2034 Reg.33'],
                'restriction_flags'    => ['coastal_zone' => false, 'heritage_zone' => false, 'flood_zone' => false],
                'permitted_uses'       => ['Large Retail', 'Malls', 'IT Parks', 'Hotels', 'Mixed-use Commercial'],
                'cost_estimates'       => [
                    'construction_cost_min_inr'    => 150000000,
                    'construction_cost_max_inr'    => 210000000,
                    'gross_development_value_inr'  => 720000000,
                    'estimated_profit_inr'         => 540000000,
                    'roi_pct'                      => 297,
                    'monthly_rent_estimate_inr'    => 9000000,
                    'annual_rent_estimate_inr'     => 108000000,
                    'breakeven_years'              => 2,
                    'construction_rate_min_sqm'    => 25000,
                    'construction_rate_max_sqm'    => 35000,
                    'note'                         => 'BKC prime commercial; Grade A office demand extremely strong.',
                ],
                'result_data'          => [
                    'summary'  => 'Highly feasible. Prime BKC location with C2 zoning and 24 m road frontage.',
                    'ai_notes' => 'Ideal for Grade-A commercial tower. SEEPZ / BKC enterprise zone benefits may apply.',
                ],
                'calculation_log'      => [
                    ['step' => 'Zone Detection', 'result' => 'C2 — Commercial (District Level)'],
                    ['step' => 'FSI Applied',     'result' => '3.0 (≥18 m road band)'],
                    ['step' => 'Max BUA',         'result' => '2000 × 3.0 = 6,000 sqm'],
                    ['step' => 'Ground Coverage', 'result' => '55% → 1,100 sqm'],
                    ['step' => 'Floors',          'result' => '14'],
                ],
            ],

            // ── 6. Completed — Industrial / IT Zone, Pune ──────────────────────
            [
                'user_id'              => $user->id,
                'state_id'             => $mh->id,
                'city_id'              => $pune?->id,
                'zone_id'              => null,
                'zone_rule_id'         => null,
                'address'              => 'Plot 42, Hinjewadi Phase II, Pune, Maharashtra 411057',
                'latitude'             => 18.5904,
                'longitude'            => 73.7368,
                'plot_area_sqm'        => 4000.0,
                'road_width_m'         => 30.0,
                'project_type'         => 'industrial',
                'max_buildable_area_sqm' => 12000.0,
                'ground_coverage_sqm'  => 1600.0,
                'max_floors'           => 8,
                'feasibility_score'    => 88,
                'status'               => 'completed',
                'setback_summary'      => ['front_m' => 6.0, 'side_m' => 3.0, 'rear_m' => 4.5, 'note' => 'DCPR 2034 Reg.58'],
                'restriction_flags'    => ['coastal_zone' => false, 'heritage_zone' => false, 'flood_zone' => false],
                'permitted_uses'       => ['IT / ITES Offices', 'Data Centres', 'BPO', 'R&D Facilities', 'Staff Hostel'],
                'cost_estimates'       => [
                    'construction_cost_min_inr'    => 240000000,
                    'construction_cost_max_inr'    => 336000000,
                    'gross_development_value_inr'  => 720000000,
                    'estimated_profit_inr'         => 432000000,
                    'roi_pct'                      => 150,
                    'monthly_rent_estimate_inr'    => 10800000,
                    'annual_rent_estimate_inr'     => 129600000,
                    'breakeven_years'              => 3,
                    'construction_rate_min_sqm'    => 20000,
                    'construction_rate_max_sqm'    => 28000,
                    'note'                         => 'Hinjewadi Phase II — IT SEZ; rental premiums apply.',
                ],
                'result_data'          => [
                    'summary'  => 'Strong feasibility. IT SEZ plot in Pune\'s top IT corridor.',
                    'ai_notes' => 'SEZ benefits include income-tax exemptions on export income for 15 years.',
                ],
                'calculation_log'      => [
                    ['step' => 'Zone Detection', 'result' => 'IT — IT/ITES Zone (manual override for SEZ)'],
                    ['step' => 'FSI Applied',     'result' => '3.0'],
                    ['step' => 'Max BUA',         'result' => '4000 × 3.0 = 12,000 sqm'],
                    ['step' => 'Ground Coverage', 'result' => '40% → 1,600 sqm'],
                    ['step' => 'Floors',          'result' => '8'],
                ],
            ],

            // ── 7. Pending ─────────────────────────────────────────────────────
            [
                'user_id'      => $user->id,
                'state_id'     => $mh->id,
                'city_id'      => $mumbai->id,
                'address'      => '22, Napean Sea Road, Malabar Hill, Mumbai, Maharashtra 400006',
                'latitude'     => 18.9642,
                'longitude'    => 72.8076,
                'plot_area_sqm' => 850.0,
                'road_width_m' => 12.0,
                'project_type' => 'residential',
                'feasibility_score' => 0,
                'status'       => 'pending',
                'result_data'  => null,
            ],

            // ── 8. Processing ──────────────────────────────────────────────────
            [
                'user_id'      => $user->id,
                'state_id'     => $mh->id,
                'city_id'      => $pune?->id,
                'address'      => 'Survey No. 112, Wakad, Pune, Maharashtra 411057',
                'latitude'     => 18.6011,
                'longitude'    => 73.7628,
                'plot_area_sqm' => 620.0,
                'road_width_m' => 9.0,
                'project_type' => 'mixed',
                'feasibility_score' => 0,
                'status'       => 'processing',
                'result_data'  => ['progress' => 'Querying zoning regulations…'],
            ],

            // ── 9. Failed ──────────────────────────────────────────────────────
            [
                'user_id'      => $user->id,
                'state_id'     => $mh->id,
                'address'      => 'Some Road, Unknown Village, Maharashtra',
                'latitude'     => 18.9220,
                'longitude'    => 72.8347,
                'plot_area_sqm' => 200.0,
                'road_width_m' => 3.0,
                'project_type' => 'residential',
                'feasibility_score' => 0,
                'status'       => 'failed',
                'result_data'  => ['error' => 'No matching zone rule found for the given coordinates and road width.'],
            ],
        ];

        foreach ($reports as $data) {
            FeasibilityReport::create($data);
        }

        $this->command->info('Feasibility report test data seeded (' . count($reports) . ' records).');
    }
}
