<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Equipment;
use App\Models\ChecklistTemplate;
use App\Models\Inspection;
use App\Models\Finding;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // Users
        $techA = User::create(['name' => 'Aderito Soares', 'role' => 'technician', 'department' => 'Telecom & Navigation', 'active' => true]);
        $techF = User::create(['name' => 'Filomena Pereira', 'role' => 'technician', 'department' => 'Telecom & Navigation', 'active' => true]);
        $techJ = User::create(['name' => 'Joaquim Da Costa', 'role' => 'technician', 'department' => 'Telecom & Navigation', 'active' => true]);
        $sup = User::create(['name' => 'Domingos Ximenes', 'role' => 'supervisor', 'department' => 'Telecom & Navigation', 'active' => true]);
        $mgr = User::create(['name' => 'Mariana Guterres', 'role' => 'management', 'department' => 'Telecom & Navigation', 'active' => true]);
        $adm = User::create(['name' => 'Sistema Admin', 'role' => 'administrator', 'department' => 'Telecom & Navigation', 'active' => true]);
        User::create(['name' => 'Paulo Belo (retired)', 'role' => 'technician', 'department' => 'Telecom & Navigation', 'active' => false]);

        // Equipment
        $eVOR = Equipment::create(['name' => 'DVOR/DME COM-50', 'type' => 'Navigation', 'location' => 'Nav Aid Field North', 'area' => 'DVOR Site', 'active' => true]);
        $eLOC = Equipment::create(['name' => 'ILS Localizer RWY 08', 'type' => 'Navigation', 'location' => 'Runway 08 Threshold', 'area' => 'ILS Site', 'active' => true]);
        $eGP = Equipment::create(['name' => 'ILS Glide Path RWY 08', 'type' => 'Navigation', 'location' => 'Runway 08 Aiming Point', 'area' => 'ILS Site', 'active' => true]);
        $eVHF = Equipment::create(['name' => 'VHF Air-Ground Radio Main', 'type' => 'Communication', 'location' => 'Control Tower', 'area' => 'Control Tower', 'active' => true]);
        $eNDB = Equipment::create(['name' => 'NDB Beacon DIL', 'type' => 'Navigation', 'location' => 'Beacon Field', 'area' => 'NDB Site', 'active' => true]);
        $eRAD = Equipment::create(['name' => 'Primary Surveillance Radar', 'type' => 'Surveillance', 'location' => 'Radar Hill', 'area' => 'Radar Site', 'active' => true]);
        $eATIS = Equipment::create(['name' => 'ATIS Broadcast Unit', 'type' => 'Communication', 'location' => 'Equipment Room', 'area' => 'Equipment Room', 'active' => true]);
        $eGEN = Equipment::create(['name' => 'Standby Generator 250kVA', 'type' => 'Power', 'location' => 'Power House', 'area' => 'Power House', 'active' => true]);
        $eUPS = Equipment::create(['name' => 'UPS Bank Equipment Room', 'type' => 'Power', 'location' => 'Equipment Room', 'area' => 'Equipment Room', 'active' => true]);
        Equipment::create(['name' => 'Old VSAT Modem (decommissioned)', 'type' => 'Communication', 'location' => 'Equipment Room', 'area' => 'Equipment Room', 'active' => false]);

        // Checklists
        $clDaily = ChecklistTemplate::create(['name' => 'Daily Communication/Nav Check', 'inspection_type' => 'daily', 'items' => ['Verify equipment is powered and ON', 'Check transmit / receive audio quality', 'Verify operating frequency / channel', 'Inspect antenna and feeder cable', 'Record power output / signal readings', 'Confirm no active alarms on panel'], 'active' => true]);
        $clWeekly = ChecklistTemplate::create(['name' => 'Weekly Facility & Power Check', 'inspection_type' => 'weekly', 'items' => ['Inspect equipment shelter and ventilation', 'Check air-conditioning / temperature log', 'Test standby generator auto-start', 'Inspect UPS battery indicators', 'Verify earthing / grounding connections', 'Clean filters and inspect for corrosion'], 'active' => true]);
        $clMonthly = ChecklistTemplate::create(['name' => 'Monthly Navigation Calibration Check', 'inspection_type' => 'monthly', 'items' => ['Verify ILS/VOR alignment within tolerance', 'Check monitor and changeover function', 'Review monthly fault and event log', 'Inspect tower lighting and obstruction lamps', 'Test remote control and monitoring link', 'Confirm calibration records are up to date'], 'active' => true]);

        $resultsAll = function ($tpl, $condition, $abnormalNote = null) {
            $items = $tpl->items;
            return collect($items)->map(function ($item, $i) use ($items, $condition, $abnormalNote) {
                $isLast = $i === count($items) - 1;
                return [
                    'item' => $item,
                    'condition' => ($abnormalNote && $isLast) ? 'abnormal' : $condition,
                    'note' => ($abnormalNote && $isLast) ? $abnormalNote : ''
                ];
            })->toArray();
        };

        $today = \Carbon\Carbon::now()->format('Y-m-d');
        $tomorrow = \Carbon\Carbon::now()->addDays(1)->format('Y-m-d');
        $nextWeek = \Carbon\Carbon::now()->addDays(7)->format('Y-m-d');
        $yesterday = \Carbon\Carbon::now()->subDays(1)->format('Y-m-d');
        $lastWeek = \Carbon\Carbon::now()->subDays(7)->format('Y-m-d');
        $lastMonth = \Carbon\Carbon::now()->subMonth()->format('Y-m-d');

        // Inspections
        Inspection::create(['title' => 'Daily check — VHF Air-Ground Radio Main', 'equipment_id' => $eVHF->id, 'inspection_type' => 'daily', 'status' => 'Assigned', 'scheduled_date' => $today, 'deadline' => $today, 'priority' => 'high', 'assigned_to' => $techA->id, 'created_by' => $sup->id, 'checklist_template_id' => $clDaily->id]);
        Inspection::create(['title' => 'Daily check — DVOR/DME COM-50', 'equipment_id' => $eVOR->id, 'inspection_type' => 'daily', 'status' => 'In Progress', 'scheduled_date' => $today, 'deadline' => $today, 'assigned_to' => $techA->id, 'created_by' => $sup->id, 'checklist_template_id' => $clDaily->id, 'started_at' => \Carbon\Carbon::now()->subHours(1)->format('Y-m-d H:i:s'), 'checklist_results' => $resultsAll($clDaily, 'normal')]);
        Inspection::create(['title' => 'Daily check — ATIS Broadcast Unit', 'equipment_id' => $eATIS->id, 'inspection_type' => 'daily', 'status' => 'Assigned', 'scheduled_date' => $today, 'assigned_to' => $techF->id, 'created_by' => $sup->id, 'checklist_template_id' => $clDaily->id]);

        Inspection::create(['title' => 'Weekly check — Standby Generator 250kVA', 'equipment_id' => $eGEN->id, 'inspection_type' => 'weekly', 'status' => 'Scheduled', 'scheduled_date' => $nextWeek, 'priority' => 'normal', 'assigned_to' => $techA->id, 'created_by' => $sup->id, 'checklist_template_id' => $clWeekly->id]);
        Inspection::create(['title' => 'Monthly calibration — ILS Localizer RWY 08', 'equipment_id' => $eLOC->id, 'inspection_type' => 'monthly', 'status' => 'Assigned', 'scheduled_date' => $nextWeek, 'priority' => 'high', 'assigned_to' => $techJ->id, 'created_by' => $sup->id, 'checklist_template_id' => $clMonthly->id]);
        Inspection::create(['title' => 'Weekly check — UPS Bank Equipment Room', 'equipment_id' => $eUPS->id, 'inspection_type' => 'weekly', 'status' => 'Scheduled', 'scheduled_date' => $tomorrow, 'assigned_to' => $techF->id, 'created_by' => $sup->id, 'checklist_template_id' => $clWeekly->id]);

        Inspection::create(['title' => 'Daily check — Primary Surveillance Radar', 'equipment_id' => $eRAD->id, 'inspection_type' => 'daily', 'status' => 'Overdue', 'scheduled_date' => $lastWeek, 'deadline' => $lastWeek, 'priority' => 'high', 'assigned_to' => $techA->id, 'created_by' => $sup->id, 'checklist_template_id' => $clDaily->id]);
        Inspection::create(['title' => 'Daily check — NDB Beacon DIL', 'equipment_id' => $eNDB->id, 'inspection_type' => 'daily', 'status' => 'Overdue', 'scheduled_date' => $yesterday, 'deadline' => $yesterday, 'assigned_to' => $techJ->id, 'created_by' => $sup->id, 'checklist_template_id' => $clDaily->id]);

        Inspection::create(['title' => 'Daily check — ILS Glide Path RWY 08', 'equipment_id' => $eGP->id, 'inspection_type' => 'daily', 'status' => 'Awaiting Validation', 'scheduled_date' => $today, 'deadline' => $today, 'assigned_to' => $techA->id, 'created_by' => $sup->id, 'checklist_template_id' => $clDaily->id, 'started_at' => \Carbon\Carbon::now()->subHours(2)->format('Y-m-d H:i:s'), 'submitted_at' => \Carbon\Carbon::now()->subMinutes(10)->format('Y-m-d H:i:s'), 'result_notes' => 'Glide path operating normally, all readings within tolerance.', 'checklist_results' => $resultsAll($clDaily, 'normal')]);

        Inspection::create(['title' => 'Weekly check — VHF Air-Ground Radio Main', 'equipment_id' => $eVHF->id, 'inspection_type' => 'weekly', 'status' => 'Needs Revision', 'scheduled_date' => $yesterday, 'deadline' => $yesterday, 'assigned_to' => $techA->id, 'created_by' => $sup->id, 'checklist_template_id' => $clWeekly->id, 'started_at' => \Carbon\Carbon::parse($yesterday)->addHours(9)->format('Y-m-d H:i:s'), 'submitted_at' => \Carbon\Carbon::parse($yesterday)->addHours(10)->format('Y-m-d H:i:s'), 'revision_notes' => 'Generator auto-start result missing a reading and no photo/evidence note. Please add and resubmit.', 'checklist_results' => $resultsAll($clWeekly, 'normal')]);

        $cmp1 = Inspection::create(['title' => 'Monthly calibration — DVOR/DME COM-50', 'equipment_id' => $eVOR->id, 'inspection_type' => 'monthly', 'status' => 'Completed', 'scheduled_date' => $lastMonth, 'deadline' => $lastMonth, 'assigned_to' => $techJ->id, 'created_by' => $sup->id, 'checklist_template_id' => $clMonthly->id, 'validated_by' => $sup->id, 'started_at' => \Carbon\Carbon::parse($lastMonth)->addHours(8)->format('Y-m-d H:i:s'), 'submitted_at' => \Carbon\Carbon::parse($lastMonth)->addHours(11)->format('Y-m-d H:i:s'), 'validated_at' => \Carbon\Carbon::parse($lastMonth)->addHours(14)->format('Y-m-d H:i:s'), 'result_notes' => 'Calibration within tolerance. Changeover tested OK.', 'checklist_results' => $resultsAll($clMonthly, 'normal')]);
        $cmp2 = Inspection::create(['title' => 'Weekly check — Standby Generator 250kVA', 'equipment_id' => $eGEN->id, 'inspection_type' => 'weekly', 'status' => 'Completed', 'scheduled_date' => $lastWeek, 'deadline' => $lastWeek, 'assigned_to' => $techA->id, 'created_by' => $sup->id, 'checklist_template_id' => $clWeekly->id, 'validated_by' => $sup->id, 'started_at' => \Carbon\Carbon::parse($lastWeek)->addHours(9)->format('Y-m-d H:i:s'), 'submitted_at' => \Carbon\Carbon::parse($lastWeek)->addHours(10)->format('Y-m-d H:i:s'), 'validated_at' => \Carbon\Carbon::parse($lastWeek)->addHours(12)->format('Y-m-d H:i:s'), 'result_notes' => 'Generator started on first attempt. Found minor coolant seepage (see finding).', 'checklist_results' => $resultsAll($clWeekly, 'abnormal', 'Minor coolant seepage near lower hose clamp.')]);
        Inspection::create(['title' => 'Daily check — ATIS Broadcast Unit', 'equipment_id' => $eATIS->id, 'inspection_type' => 'daily', 'status' => 'Completed', 'scheduled_date' => $yesterday, 'deadline' => $yesterday, 'assigned_to' => $techF->id, 'created_by' => $sup->id, 'checklist_template_id' => $clDaily->id, 'validated_by' => $sup->id, 'started_at' => \Carbon\Carbon::parse($yesterday)->addHours(8)->format('Y-m-d H:i:s'), 'submitted_at' => \Carbon\Carbon::parse($yesterday)->addHours(8)->addMinutes(45)->format('Y-m-d H:i:s'), 'validated_at' => \Carbon\Carbon::parse($yesterday)->addHours(9)->addMinutes(30)->format('Y-m-d H:i:s'), 'result_notes' => 'ATIS broadcasting normally.', 'checklist_results' => $resultsAll($clDaily, 'normal')]);

        // Findings
        Finding::create(['inspection_id' => $cmp2->id, 'equipment_id' => $eGEN->id, 'description' => 'Coolant seepage at standby generator lower hose clamp.', 'location' => 'Power House', 'urgency' => 'high', 'status' => 'Assigned for Follow-Up', 'evidence_note' => 'Photo logged: damp residue under clamp.', 'recommendation' => 'Replace hose clamp and top up coolant.', 'assigned_to' => $techA->id, 'follow_up_notes' => 'Spare clamp requested from store.', 'created_by' => $techA->id]);
        Finding::create(['inspection_id' => $cmp1->id, 'equipment_id' => $eVOR->id, 'description' => 'DVOR monitor showing intermittent low-level alarm overnight.', 'location' => 'DVOR Site', 'urgency' => 'critical', 'status' => 'Escalated', 'evidence_note' => 'Event log entries attached.', 'recommendation' => 'Escalate to division head; may affect approach guidance.', 'assigned_to' => $techJ->id, 'follow_up_notes' => 'Escalated to management for vendor support decision.', 'created_by' => $techJ->id]);
        Finding::create(['inspection_id' => null, 'equipment_id' => $eRAD->id, 'description' => 'Radar cooling fan noise increasing — possible bearing wear.', 'location' => 'Radar Site', 'urgency' => 'medium', 'status' => 'In Follow-Up', 'recommendation' => 'Schedule fan replacement during next maintenance window.', 'assigned_to' => $techA->id, 'follow_up_notes' => 'Replacement fan on order.', 'created_by' => $sup->id]);
        Finding::create(['inspection_id' => null, 'equipment_id' => $eUPS->id, 'description' => 'UPS battery bank temperature slightly high.', 'location' => 'Equipment Room', 'urgency' => 'medium', 'status' => 'Resolved', 'recommendation' => 'Improve room ventilation.', 'assigned_to' => $techF->id, 'follow_up_notes' => 'Extra exhaust fan installed.', 'completion_evidence' => 'Temperature back to normal range; verified over 3 days.', 'created_by' => $techF->id]);
        Finding::create(['inspection_id' => null, 'equipment_id' => $eNDB->id, 'description' => 'NDB antenna guy-wire tension below spec.', 'location' => 'NDB Site', 'urgency' => 'low', 'status' => 'Closed', 'recommendation' => 'Re-tension guy wires.', 'assigned_to' => $techJ->id, 'follow_up_notes' => 'Guy wires re-tensioned.', 'completion_evidence' => 'Tension within spec; supervisor verified.', 'created_by' => $techJ->id]);
        Finding::create(['inspection_id' => null, 'equipment_id' => $eVHF->id, 'description' => 'VHF main transmitter occasional audio crackle on transmit.', 'location' => 'Control Tower', 'urgency' => 'high', 'status' => 'Awaiting Review', 'evidence_note' => 'Audio sample noted by tower controller.', 'recommendation' => 'Inspect connectors and switch to standby for testing.', 'created_by' => $techA->id]);
    }
}
