<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Appointment;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\SpecialtyClinicalRecord;
use App\Models\User;
use App\Models\Visit;
use App\Services\Care\SpecialtyModuleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CareAmbulanceSuiteTest extends TestCase
{
    use RefreshDatabase;

    protected User $owner;

    protected Organization $organization;

    protected Branch $branch;

    protected Patient $patient;

    protected Visit $visit;

    protected function setUp(): void
    {
        parent::setUp();
        $this->withoutMiddleware(EnsurePlatformSession::class);

        $this->owner = User::create([
            'public_id' => 'amb-owner',
            'name' => 'Owner',
            'email' => 'amb-owner@example.com',
        ]);

        $this->organization = Organization::create([
            'owner_ref' => $this->owner->public_id,
            'name' => 'Ambulance Clinic',
            'slug' => 'ambulance-clinic',
            'settings' => [
                'onboarded' => true,
                'facility_type' => 'clinic',
                'plan' => 'pro',
                'plan_expires_at' => now()->addMonth()->toIso8601String(),
                'queue_integration_enabled' => true,
            ],
        ]);

        Member::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'user_ref' => $this->owner->public_id,
            'role' => 'hospital_admin',
            'branch_id' => null,
        ]);

        $this->branch = Branch::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'name' => 'Main',
            'is_active' => true,
        ]);

        app(SpecialtyModuleService::class)->activate(
            $this->organization,
            $this->owner->public_id,
            'ambulance',
        );

        $department = Department::query()
            ->where('branch_id', $this->branch->id)
            ->where('type', 'ambulance')
            ->firstOrFail();

        $this->patient = Patient::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_number' => 'P-AMB-SUITE',
            'first_name' => 'Kojo',
            'last_name' => 'Mensah',
            'gender' => 'male',
            'date_of_birth' => '1985-03-20',
        ]);

        $this->visit = Visit::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_id' => $this->patient->id,
            'status' => Visit::STATUS_IN_PROGRESS,
            'checked_in_at' => now(),
            'specialty_stage' => 'check_in',
        ]);

        Appointment::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_id' => $this->patient->id,
            'department_id' => $department->id,
            'visit_id' => $this->visit->id,
            'type' => Appointment::TYPE_WALK_IN,
            'status' => Appointment::STATUS_IN_CONSULTATION,
            'scheduled_at' => now(),
            'waiting_at' => now(),
            'checked_in_at' => now(),
            'started_at' => now(),
        ]);
    }

    public function test_overview_and_scene_tabs_render(): void
    {
        $this->actingAs($this->owner)
            ->get(route('care.specialty.workspace', [
                'module' => 'ambulance',
                'visit' => $this->visit,
                'tab' => 'overview',
            ]))
            ->assertOk()
            ->assertSee('Ambulance overview')
            ->assertSee('data-care-stage-bar', false)
            ->assertSee('Scene / triage')
            ->assertSee('Dispatch')
            ->assertSee('Ambulance reports');

        $this->actingAs($this->owner)
            ->get(route('care.specialty.workspace', [
                'module' => 'ambulance',
                'visit' => $this->visit,
                'tab' => 'scene',
            ]))
            ->assertOk()
            ->assertSee('Chief complaint')
            ->assertSee('Scene findings');
    }

    public function test_scene_sets_stage_and_acuity_alert(): void
    {
        $this->actingAs($this->owner)
            ->post(route('care.specialty.clinical.save', [
                'module' => 'ambulance',
                'visit' => $this->visit,
            ]), [
                'tab' => 'scene',
                'payload' => [
                    'chief_complaint' => 'Chest pain',
                    'acuity' => 'Critical',
                    'mechanism' => 'Sudden onset at home',
                    'airway_ok' => '1',
                    'breathing_ok' => '1',
                    'circulation_ok' => '0',
                    'gcs' => '15',
                    'vitals_summary' => 'BP 90/60, HR 120, SpO2 92%',
                    'scene_findings' => 'Diaphoretic, pale, ongoing chest pain',
                    'hazards' => 'None',
                ],
            ])
            ->assertRedirect();

        $this->assertSame('on_scene', $this->visit->fresh()->specialty_stage);

        $record = SpecialtyClinicalRecord::query()
            ->where('visit_id', $this->visit->id)
            ->where('record_type', 'amb_scene')
            ->firstOrFail();

        $codes = collect($record->alerts)->pluck('code')->all();
        $this->assertContains('amb.acuity_high', $codes);
    }

    public function test_stage_advance_and_handover_completes_visit(): void
    {
        $this->actingAs($this->owner)
            ->post(route('care.specialty.ambulance.stage', $this->visit), [
                'stage' => 'handover',
            ])
            ->assertRedirect(route('care.specialty.workspace', [
                'module' => 'ambulance',
                'visit' => $this->visit,
                'tab' => 'handover',
            ]));

        $this->assertSame('handover', $this->visit->fresh()->specialty_stage);

        $this->actingAs($this->owner)
            ->post(route('care.specialty.ambulance.handover', $this->visit), [
                'tab' => 'handover',
                'payload' => [
                    'receiving_facility' => 'Korle Bu ED',
                    'receiving_clinician' => 'Dr. Boateng',
                    'handover_summary' => 'S: Chest pain. B: Sudden onset. A: Critical acuity. R: Handed over to ED resus.',
                    'outcome' => 'Completed — handed over',
                    'time_critical' => 'STEMI',
                    'follow_up' => 'PCR filed',
                ],
            ])
            ->assertRedirect(route('care.specialty.workspace', [
                'module' => 'ambulance',
                'visit' => $this->visit,
                'tab' => 'handover',
            ]));

        $this->assertSame('completed', $this->visit->fresh()->specialty_stage);
        $this->assertSame(Visit::STATUS_COMPLETED, $this->visit->fresh()->status);
        $this->assertDatabaseHas('care_specialty_clinical_records', [
            'visit_id' => $this->visit->id,
            'record_type' => 'amb_handover',
            'status' => SpecialtyClinicalRecord::STATUS_COMPLETED,
        ]);
    }

    public function test_reports_and_print(): void
    {
        $this->actingAs($this->owner)
            ->get(route('care.specialty.ambulance.reports'))
            ->assertOk()
            ->assertSee('Ambulance reports')
            ->assertSee('Arrivals today');

        $this->actingAs($this->owner)
            ->get(route('care.specialty.ambulance.print', $this->visit))
            ->assertOk()
            ->assertSee('Ambulance summary')
            ->assertSee($this->patient->fullName());
    }

    public function test_list_index_does_not_auto_open_patient(): void
    {
        $this->actingAs($this->owner)
            ->get(route('care.specialty.show', 'ambulance'))
            ->assertOk()
            ->assertDontSee('Ambulance overview');
    }

    public function test_home_shows_dispatch_board_not_call_next(): void
    {
        $this->actingAs($this->owner)
            ->get(route('care.specialty.show', 'ambulance'))
            ->assertOk()
            ->assertSee('Dispatch board')
            ->assertSee('New call')
            ->assertSee('Dispatched')
            ->assertSee('On scene')
            ->assertSee('Transport')
            ->assertSee('Handover')
            ->assertSee($this->patient->fullName())
            ->assertDontSee('Call next')
            ->assertDontSee('Bring the next waiting patient to your desk')
            ->assertSee(route('care.specialty.ambulance.new-call'), false);
    }

    public function test_ambulance_staff_can_log_new_call_without_appointments_manage(): void
    {
        $user = User::create([
            'public_id' => 'amb-crew',
            'name' => 'Kojo Ambulance',
            'email' => 'kojo-amb@example.com',
        ]);
        Member::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'user_ref' => $user->public_id,
            'role' => 'ambulance_staff',
            'branch_id' => $this->branch->id,
        ]);

        $this->actingAs($user)
            ->get(route('care.appointments.walk-in.create'))
            ->assertForbidden();

        $this->actingAs($user)
            ->get(route('care.specialty.ambulance.new-call'))
            ->assertOk()
            ->assertSee('Log a new call');

        $this->actingAs($user)
            ->post(route('care.specialty.ambulance.new-call.store'), [
                'branch_id' => $this->branch->id,
                'patient_id' => $this->patient->id,
                'reason' => 'Chest pain',
                'location' => 'Spintex Road',
            ])
            ->assertRedirect(route('care.specialty.show', 'ambulance'));

        $this->assertDatabaseHas('care_appointments', [
            'patient_id' => $this->patient->id,
            'branch_id' => $this->branch->id,
            'type' => Appointment::TYPE_WALK_IN,
        ]);

        $visit = Visit::query()
            ->where('patient_id', $this->patient->id)
            ->where('specialty_stage', 'check_in')
            ->latest('id')
            ->first();
        $this->assertNotNull($visit);
    }
}
