<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Assessment;
use App\Models\AssessmentTemplate;
use App\Models\Branch;
use App\Models\CareUnit;
use App\Models\Department;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\User;
use App\Models\Visit;
use App\Models\VisitVital;
use App\Services\Care\AssessmentService;
use App\Services\Care\VisitPlacementService;
use Database\Seeders\AssessmentTemplateSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CareNursingAssessmentsAndPerformanceTest extends TestCase
{
    use RefreshDatabase;

    protected User $owner;

    protected Organization $organization;

    protected CareUnit $unit;

    protected Visit $visit;

    protected Patient $patient;

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

        $this->seed(AssessmentTemplateSeeder::class);

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

        $this->organization = Organization::create([
            'owner_ref' => $this->owner->public_id,
            'name' => 'Nursing DE Hospital',
            'slug' => 'nursing-de-hospital',
            'settings' => [
                'onboarded' => true,
                'facility_type' => 'hospital',
                'plan' => 'pro',
                'plan_expires_at' => now()->addMonth()->toIso8601String(),
                'rollout' => ['assessments_engine' => true],
            ],
        ]);

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

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

        $department = Department::create([
            'owner_ref' => $this->owner->public_id,
            'branch_id' => $branch->id,
            'name' => 'Medicine',
            'type' => 'general',
            'is_active' => true,
        ]);

        $this->unit = CareUnit::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'department_id' => $department->id,
            'name' => 'Medical Ward',
            'kind' => 'inpatient',
            'is_active' => true,
        ]);

        $this->patient = Patient::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $branch->id,
            'patient_number' => 'P-NDE-1',
            'first_name' => 'Ama',
            'last_name' => 'Mensah',
            'gender' => 'female',
        ]);

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

        app(VisitPlacementService::class)->place(
            $this->visit,
            $this->unit,
            null,
            $this->owner->public_id,
            $this->owner->public_id,
        );
    }

    public function test_nursing_packs_are_seeded(): void
    {
        foreach (['news2', 'braden', 'morse', 'pain_nrs'] as $code) {
            $this->assertNotNull(
                AssessmentTemplate::currentSystemByCode($code),
                "Missing nursing pack {$code}",
            );
        }
    }

    public function test_start_nursing_assessment_from_unit_board(): void
    {
        $this->actingAs($this->owner)
            ->post(route('care.care-units.assessments.start', [$this->unit, $this->visit]), [
                'template_code' => 'news2',
            ])
            ->assertRedirect();

        $assessment = Assessment::query()->where('visit_id', $this->visit->id)->first();
        $this->assertNotNull($assessment);
        $this->assertSame(Assessment::STATUS_DRAFT, $assessment->status);
        $this->assertSame('news2', $assessment->template->code);

        $this->actingAs($this->owner)
            ->get(route('care.care-units.assessments', $this->unit))
            ->assertOk()
            ->assertSee('Ama')
            ->assertSee('NEWS2');
    }

    public function test_record_visit_vitals_and_performance_dashboard(): void
    {
        $this->actingAs($this->owner)
            ->post(route('care.care-units.vitals.store', [$this->unit, $this->visit]), [
                'bp_systolic' => 120,
                'bp_diastolic' => 80,
                'pulse' => 72,
                'spo2' => 98,
                'respiratory_rate' => 16,
                'temperature' => 36.8,
            ])
            ->assertRedirect(route('care.care-units.assessments', $this->unit));

        $this->assertDatabaseHas('care_visit_vitals', [
            'visit_id' => $this->visit->id,
            'pulse' => 72,
            'care_unit_id' => $this->unit->id,
        ]);

        $member = Member::query()->where('user_ref', $this->owner->public_id)->first();
        $assessment = app(AssessmentService::class)->start(
            $this->patient,
            'pain_nrs',
            $this->owner->public_id,
            $member,
            ['visit' => $this->visit->fresh(), 'actor' => $this->owner->public_id],
        );

        $this->actingAs($this->owner)
            ->put(route('care.assessments.update', $assessment), [
                'answers' => ['pain_score' => 4],
            ])
            ->assertRedirect();

        $this->actingAs($this->owner)
            ->post(route('care.assessments.complete', $assessment))
            ->assertRedirect();

        $assessment->refresh()->load('score');
        $this->assertSame(Assessment::STATUS_COMPLETED, $assessment->status);
        $this->assertNotNull($assessment->score);
        $this->assertSame('Moderate', $assessment->score->severity_label);

        $this->actingAs($this->owner)
            ->get(route('care.care-units.performance', $this->unit))
            ->assertOk()
            ->assertSee('Unit nursing KPIs')
            ->assertSee('Assessments done');
    }

    public function test_visit_vitals_model_created(): void
    {
        VisitVital::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'visit_id' => $this->visit->id,
            'patient_id' => $this->patient->id,
            'care_unit_id' => $this->unit->id,
            'pulse' => 80,
            'recorded_at' => now(),
            'recorded_by' => $this->owner->public_id,
        ]);

        $this->assertSame(1, VisitVital::query()->where('visit_id', $this->visit->id)->count());
    }
}
