<?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\Models\VitalSign;
use App\Services\Care\SpecialtyModuleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CareEmergencySuiteTest 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' => 'er-owner',
            'name' => 'Owner',
            'email' => 'er-owner@example.com',
        ]);

        $this->organization = Organization::create([
            'owner_ref' => $this->owner->public_id,
            'name' => 'Emergency Clinic',
            'slug' => 'emergency-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,
            'emergency',
        );

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

        $this->patient = Patient::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_number' => 'P-ER-SUITE',
            'first_name' => 'Kwame',
            'last_name' => 'Boateng',
            'gender' => 'male',
            'date_of_birth' => '1988-01-01',
        ]);

        $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' => 'arrival',
        ]);

        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_vitals_tabs_render(): void
    {
        $this->actingAs($this->owner)
            ->get(route('care.specialty.workspace', [
                'module' => 'emergency',
                'visit' => $this->visit,
                'tab' => 'overview',
            ]))
            ->assertOk()
            ->assertSee('Emergency overview')
            ->assertSee('data-care-stage-bar', false)
            ->assertSee('Arrival / triage')
            ->assertSee('Move to treatment')
            ->assertSee('ED reports');

        $this->actingAs($this->owner)
            ->get(route('care.specialty.workspace', [
                'module' => 'emergency',
                'visit' => $this->visit,
                'tab' => 'vitals',
            ]))
            ->assertOk()
            ->assertSee('Save vitals');
    }

    public function test_triage_sets_stage_and_alerts(): void
    {
        $this->actingAs($this->owner)
            ->post(route('care.specialty.clinical.save', [
                'module' => 'emergency',
                'visit' => $this->visit,
            ]), [
                'tab' => 'triage',
                'payload' => [
                    'acuity' => '1 - Resuscitation',
                    'chief_complaint' => 'Chest pain',
                    'airway_ok' => '1',
                    'breathing_ok' => '0',
                    'circulation_ok' => '1',
                    'pain_score' => 9,
                    'disposition_intent' => 'Resus',
                ],
            ])
            ->assertRedirect();

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

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

        $codes = collect($record->alerts)->pluck('code')->all();
        $this->assertContains('er.high_acuity', $codes);
        $this->assertContains('er.abc_compromise', $codes);
        $this->assertContains('er.severe_pain', $codes);
    }

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

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

        $this->actingAs($this->owner)
            ->post(route('care.specialty.emergency.vitals', $this->visit), [
                'bp_systolic' => 120,
                'bp_diastolic' => 80,
                'pulse' => 88,
                'spo2' => 98,
            ])
            ->assertRedirect(route('care.specialty.workspace', [
                'module' => 'emergency',
                'visit' => $this->visit,
                'tab' => 'vitals',
            ]));

        $this->assertDatabaseHas('care_vital_signs', [
            'bp_systolic' => 120,
            'pulse' => 88,
        ]);
        $this->assertTrue(VitalSign::query()->where('bp_systolic', 120)->exists());

        $this->actingAs($this->owner)
            ->post(route('care.specialty.emergency.disposition', $this->visit), [
                'tab' => 'disposition',
                'payload' => [
                    'disposition' => 'Discharge home',
                    'condition' => 'Stable',
                    'diagnosis' => 'Musculoskeletal chest wall pain',
                    'advice' => 'Return if worsens',
                ],
            ])
            ->assertRedirect();

        $this->assertSame('disposition', $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' => 'disposition',
            'status' => SpecialtyClinicalRecord::STATUS_COMPLETED,
        ]);
    }

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

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