<?php

namespace Tests\Feature;

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

class CareBranchContextTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

    protected Organization $organization;

    protected Branch $east;

    protected Branch $west;

    protected Patient $eastPatient;

    protected Patient $westPatient;

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

        $this->user = User::create([
            'public_id' => 'test-admin-001',
            'name' => 'Hospital Admin',
            'email' => 'admin@example.com',
        ]);

        $this->organization = Organization::create([
            'owner_ref' => $this->user->public_id,
            'name' => 'Multi Branch Clinic',
            'slug' => 'multi-branch',
            'timezone' => 'UTC',
            'settings' => ['onboarded' => true, 'plan' => 'pro', 'plan_expires_at' => now()->addMonth()->toIso8601String()],
        ]);

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

        $this->east = Branch::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'name' => 'East Legon Care',
            'is_active' => true,
        ]);

        $this->west = Branch::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'name' => 'West Hills Care',
            'is_active' => true,
        ]);

        foreach ([$this->east, $this->west] as $branch) {
            Department::create([
                'owner_ref' => $this->user->public_id,
                'branch_id' => $branch->id,
                'name' => 'Pharmacy',
                'type' => 'pharmacy',
                'is_active' => true,
            ]);
        }

        $this->eastPatient = $this->makePatient($this->east, 'Ama', 'East', 'LC-EAST-1');
        $this->westPatient = $this->makePatient($this->west, 'Kofi', 'West', 'LC-WEST-1');

        $this->makeWaitingAppointment($this->east, $this->eastPatient);
        $this->makeWaitingAppointment($this->west, $this->westPatient);
        $this->makeActivePrescription($this->east, $this->eastPatient, 'East Med');
        $this->makeActivePrescription($this->west, $this->westPatient, 'West Med');
    }

    public function test_admin_branch_filter_persists_from_pharmacy_to_lab(): void
    {
        // hospital_admin cannot open the patient-flow board; pharmacy/lab still share BranchContext.
        $this->actingAs($this->user)
            ->get(route('care.prescriptions.queue', ['branch_id' => $this->west->id]))
            ->assertOk()
            ->assertSee('West Hills Care')
            ->assertSee('West Med')
            ->assertSee('Kofi West')
            ->assertDontSee('East Med')
            ->assertDontSee('Ama East');

        $this->assertSame(
            $this->west->id,
            (int) session(BranchContext::SESSION_KEY),
        );

        $this->actingAs($this->user)
            ->get(route('care.lab.queue.index'))
            ->assertOk()
            ->assertSee('West Hills Care')
            ->assertSee('selected>West Hills Care', false);
    }

    public function test_pharmacy_queue_branch_filter_scopes_list_for_admin(): void
    {
        $this->actingAs($this->user)
            ->get(route('care.prescriptions.queue', ['branch_id' => $this->east->id]))
            ->assertOk()
            ->assertSee('East Legon Care')
            ->assertSee('East Med')
            ->assertDontSee('West Med');
    }

    protected function makePatient(Branch $branch, string $first, string $last, string $number): Patient
    {
        return Patient::create([
            'uuid' => (string) \Illuminate\Support\Str::uuid(),
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $branch->id,
            'patient_number' => $number,
            'first_name' => $first,
            'last_name' => $last,
        ]);
    }

    protected function makeWaitingAppointment(Branch $branch, Patient $patient): void
    {
        Appointment::create([
            'uuid' => (string) \Illuminate\Support\Str::uuid(),
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $branch->id,
            'patient_id' => $patient->id,
            'status' => Appointment::STATUS_WAITING,
            'scheduled_at' => now(),
            'waiting_at' => now(),
            'reason' => 'Check-up',
        ]);
    }

    protected function makeActivePrescription(Branch $branch, Patient $patient, string $medName): void
    {
        $visit = Visit::create([
            'uuid' => (string) \Illuminate\Support\Str::uuid(),
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $branch->id,
            'patient_id' => $patient->id,
            'status' => Visit::STATUS_IN_PROGRESS,
            'checked_in_at' => now(),
        ]);

        $consultation = Consultation::create([
            'uuid' => (string) \Illuminate\Support\Str::uuid(),
            'owner_ref' => $this->user->public_id,
            'visit_id' => $visit->id,
            'patient_id' => $patient->id,
            'status' => Consultation::STATUS_DRAFT,
            'started_at' => now(),
        ]);

        $prescription = Prescription::create([
            'uuid' => (string) \Illuminate\Support\Str::uuid(),
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'visit_id' => $visit->id,
            'consultation_id' => $consultation->id,
            'patient_id' => $patient->id,
            'status' => Prescription::STATUS_ACTIVE,
            'prescribed_by' => $this->user->public_id,
        ]);

        $prescription->items()->create([
            'owner_ref' => $this->user->public_id,
            'name' => $medName,
            'dosage' => '1 tablet',
            'frequency' => 'OD',
            'duration' => '3 days',
        ]);
    }
}
