<?php

namespace Modules\Vrc\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Modules\Vrc\Entities\VrcDocument;
use Modules\Vrc\Entities\VrcHazard;
use Modules\Vrc\Entities\VrcRepairOrderService;
use Modules\Vrc\Entities\VrcSafetyTraining;
use Modules\Vrc\Entities\VrcTechnician;
use Modules\Vrc\Entities\VrcWasteStream;
use Modules\Vrc\Entities\VrcWorkCenter;

/**
 * Demo content for the Phase 1-5 expansion (work centers + stage routing, ISO
 * 9001/14001/45001 starter records). Idempotent — guarded by the presence of the
 * seeded work centers. Safe to run repeatedly.
 */
class VrcExpansionDemoSeeder extends Seeder
{
    public function run(): void
    {
        $businessId = (int) (\App\Business::min('id') ?? 0);
        if (! $businessId) {
            return;
        }

        if (VrcWorkCenter::where('business_id', $businessId)->exists()) {
            $this->command?->info('VRC expansion demo already present — skipping.');
            return;
        }

        // Work centers (the workshop board columns).
        $centers = [
            ['name' => 'Mechanical', 'type' => 'mechanical', 'color' => '#3c8dbc', 'sort_order' => 1],
            ['name' => 'Body & Paint', 'type' => 'body_paint', 'color' => '#f39c12', 'sort_order' => 2],
            ['name' => 'Electrical', 'type' => 'electrical', 'color' => '#00a65a', 'sort_order' => 3],
            ['name' => 'Diagnostics', 'type' => 'diagnostics', 'color' => '#605ca8', 'sort_order' => 4],
            ['name' => 'Quality Control', 'type' => 'qc', 'color' => '#dd4b39', 'sort_order' => 5],
        ];
        $ids = [];
        foreach ($centers as $c) {
            $ids[] = VrcWorkCenter::create($c + ['business_id' => $businessId, 'is_active' => true])->id;
        }

        // Route a few open repair-order task lines onto the board so it isn't empty.
        $lines = VrcRepairOrderService::where('vrc_repair_order_services.business_id', $businessId)
            ->join('vrc_repair_orders as ro', 'ro.id', '=', 'vrc_repair_order_services.repair_order_id')
            ->whereNotIn('ro.status', ['completed', 'cancelled', 'delivered'])
            ->select('vrc_repair_order_services.*')->limit(12)->get();
        foreach ($lines as $i => $line) {
            $line->update([
                'work_center_id'   => $ids[$i % count($ids)],
                'stage_status'     => ['queued', 'in_progress', 'done'][$i % 3],
                'stage_entered_at' => now(),
            ]);
        }

        // ISO 14001 — waste streams.
        foreach ([
            ['name' => 'Used Engine Oil', 'type' => 'used_oil', 'unit' => 'L'],
            ['name' => 'Lead-Acid Batteries', 'type' => 'battery', 'unit' => 'pcs'],
            ['name' => 'Scrap Tyres', 'type' => 'tyre', 'unit' => 'pcs'],
            ['name' => 'Brake Cleaner / Solvent', 'type' => 'solvent', 'unit' => 'L'],
        ] as $w) {
            VrcWasteStream::create($w + ['business_id' => $businessId, 'is_hazardous' => true, 'is_active' => true]);
        }

        // ISO 45001 — a sample hazard with computed risk band.
        [$score, $band] = VrcHazard::level(3, 4);
        VrcHazard::create([
            'business_id' => $businessId, 'area' => 'Paint booth', 'hazard' => 'Solvent vapour inhalation',
            'risk_description' => 'Exposure to VOCs during spray painting.',
            'likelihood' => 3, 'severity' => 4, 'risk_score' => $score, 'risk_level' => $band,
            'controls' => 'Extraction, PPE (respirator), training.', 'status' => 'open',
            'review_due' => now()->addMonths(6)->toDateString(),
        ]);

        // ISO 9001 — a sample controlled SOP.
        VrcDocument::create([
            'business_id' => $businessId, 'code' => 'SOP-001', 'title' => 'Vehicle Intake & Inspection',
            'category' => 'sop', 'version' => '1.0', 'status' => 'approved',
            'content' => 'Standard procedure for receiving a vehicle, recording condition and odometer.',
            'review_due' => now()->addYear()->toDateString(),
        ]);

        // ISO 45001 — a safety training record for the demo technician.
        $tech = VrcTechnician::where('business_id', $businessId)->first();
        if ($tech) {
            VrcSafetyTraining::create([
                'business_id' => $businessId, 'technician_id' => $tech->id,
                'course' => 'Workshop Health & Safety Induction', 'provider' => 'Internal',
                'completed_on' => now()->subMonths(2)->toDateString(),
                'expires_on' => now()->addMonths(10)->toDateString(), 'status' => 'valid',
            ]);
        }

        $this->command?->info('VRC expansion demo seeded (work centers, ISO 9001/14001/45001 samples).');
    }
}
