<?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 CarePhysiotherapySuiteTest 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' => 'pt-owner',
            'name' => 'Owner',
            'email' => 'pt-owner@example.com',
        ]);

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

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

        $this->patient = Patient::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_number' => 'P-PT-SUITE',
            'first_name' => 'Kwame',
            'last_name' => 'Asante',
            'gender' => 'male',
            'date_of_birth' => '1988-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_assessment_tabs_render(): void
    {
        $this->actingAs($this->owner)
            ->get(route('care.specialty.workspace', [
                'module' => 'physiotherapy',
                'visit' => $this->visit,
                'tab' => 'overview',
            ]))
            ->assertOk()
            ->assertSee('Physiotherapy overview')
            ->assertSee('data-care-stage-bar', false)
            ->assertSee('Check-in')
            ->assertSee('Treatment plan')
            ->assertSee('Start assessment')
            ->assertSee('Physio reports');

        $this->actingAs($this->owner)
            ->get(route('care.specialty.workspace', [
                'module' => 'physiotherapy',
                'visit' => $this->visit,
                'tab' => 'assessment',
            ]))
            ->assertOk()
            ->assertSee('Presenting complaint')
            ->assertSee('Pain score');
    }

    public function test_assessment_sets_stage_and_pain_alerts(): void
    {
        $this->actingAs($this->owner)
            ->post(route('care.specialty.clinical.save', [
                'module' => 'physiotherapy',
                'visit' => $this->visit,
            ]), [
                'tab' => 'assessment',
                'payload' => [
                    'chief_complaint' => 'Low back pain',
                    'pain_score' => 9,
                    'body_region' => 'Back / lumbar',
                    'goals' => 'Walk without pain',
                    'red_flags' => 'Night pain',
                ],
            ])
            ->assertRedirect();

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

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

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

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

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

        $this->actingAs($this->owner)
            ->post(route('care.specialty.physiotherapy.session', $this->visit), [
                'tab' => 'session',
                'payload' => [
                    'modalities' => 'Manual therapy + exercise',
                    'exercises' => 'Core activation',
                    'pain_before' => 8,
                    'pain_after' => 3,
                    'outcome' => 'Completed — discharge ready',
                    'next_review' => 'PRN',
                ],
            ])
            ->assertRedirect(route('care.specialty.workspace', [
                'module' => 'physiotherapy',
                'visit' => $this->visit,
                'tab' => 'session',
            ]));

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

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

        $this->actingAs($this->owner)
            ->get(route('care.specialty.physiotherapy.print', $this->visit))
            ->assertOk()
            ->assertSee('Physiotherapy 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', 'physiotherapy'))
            ->assertOk()
            ->assertDontSee('Physiotherapy overview');
    }
}
