<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Appointment;
use App\Models\Branch;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\Practitioner;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CareStaffTenantScopeTest extends TestCase
{
    use RefreshDatabase;

    public function test_staff_doctor_sees_only_assigned_patients_without_branch_filter(): void
    {
        $this->withoutMiddleware(EnsurePlatformSession::class);

        $owner = User::create([
            'public_id' => 'demo-pro-owner',
            'name' => 'Demo Pro Owner',
            'email' => 'demo-pro@ladill.com',
        ]);

        $doctor = User::create([
            'public_id' => 'demo-pro-doctor-pid',
            'name' => 'Demo Pro Doctor',
            'email' => 'demo-pro-doctor@ladill.com',
        ]);

        $organization = Organization::create([
            'owner_ref' => $owner->public_id,
            'name' => 'Demo Pro Clinic',
            'slug' => 'demo-pro-clinic',
            'timezone' => 'UTC',
            'settings' => [
                'onboarded' => true,
                'plan' => 'pro',
                'plan_expires_at' => now()->addMonth()->toIso8601String(),
            ],
        ]);

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

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

        $doctorMember = Member::create([
            'owner_ref' => $owner->public_id,
            'organization_id' => $organization->id,
            'user_ref' => $doctor->public_id,
            'role' => 'doctor',
            'branch_id' => $branch->id,
        ]);

        $mine = Practitioner::create([
            'owner_ref' => $owner->public_id,
            'organization_id' => $organization->id,
            'branch_id' => $branch->id,
            'member_id' => $doctorMember->id,
            'user_ref' => $doctor->public_id,
            'name' => 'Demo Pro Doctor',
            'is_active' => true,
        ]);
        $mine->syncAssignedBranches([$branch->id]);

        $other = Practitioner::create([
            'owner_ref' => $owner->public_id,
            'organization_id' => $organization->id,
            'branch_id' => $branch->id,
            'name' => 'Other Doctor',
            'is_active' => true,
        ]);
        $other->syncAssignedBranches([$branch->id]);

        $assignedPatient = Patient::create([
            'uuid' => (string) \Illuminate\Support\Str::uuid(),
            'owner_ref' => $owner->public_id,
            'organization_id' => $organization->id,
            'branch_id' => $branch->id,
            'patient_number' => 'DEMO-8883-00001',
            'first_name' => 'Ama',
            'last_name' => 'Mensah',
        ]);

        $otherPatient = Patient::create([
            'uuid' => (string) \Illuminate\Support\Str::uuid(),
            'owner_ref' => $owner->public_id,
            'organization_id' => $organization->id,
            'branch_id' => $branch->id,
            'patient_number' => 'DEMO-8883-00002',
            'first_name' => 'Kofi',
            'last_name' => 'Boateng',
        ]);

        Appointment::create([
            'uuid' => (string) \Illuminate\Support\Str::uuid(),
            'owner_ref' => $owner->public_id,
            'organization_id' => $organization->id,
            'branch_id' => $branch->id,
            'patient_id' => $assignedPatient->id,
            'practitioner_id' => $mine->id,
            'type' => Appointment::TYPE_WALK_IN,
            'status' => Appointment::STATUS_WAITING,
            'scheduled_at' => now(),
            'waiting_at' => now(),
            'queue_position' => 1,
            'reason' => 'Toothache',
            'created_by' => $owner->public_id,
        ]);

        Appointment::create([
            'uuid' => (string) \Illuminate\Support\Str::uuid(),
            'owner_ref' => $owner->public_id,
            'organization_id' => $organization->id,
            'branch_id' => $branch->id,
            'patient_id' => $otherPatient->id,
            'practitioner_id' => $other->id,
            'type' => Appointment::TYPE_WALK_IN,
            'status' => Appointment::STATUS_WAITING,
            'scheduled_at' => now(),
            'waiting_at' => now(),
            'queue_position' => 2,
            'reason' => 'Fever',
            'created_by' => $owner->public_id,
        ]);

        $this->actingAs($doctor)
            ->get(route('care.queue.index'))
            ->assertOk()
            ->assertSee('Assigned to you')
            ->assertSee('East Legon Care')
            ->assertDontSee('All practitioners')
            ->assertDontSee('name="branch_id"', false)
            ->assertDontSee('<select', false)
            ->assertSee('Ama Mensah')
            ->assertSee('Toothache')
            ->assertDontSee('Kofi Boateng')
            ->assertDontSee('Fever');

        // Even if Identity clears member.branch_id, doctors stay on their desk's branch — no picker.
        $doctorMember->update(['branch_id' => null]);
        Branch::create([
            'owner_ref' => $owner->public_id,
            'organization_id' => $organization->id,
            'name' => 'West Hills Care',
            'is_active' => true,
        ]);

        $this->actingAs($doctor)
            ->get(route('care.queue.index'))
            ->assertOk()
            ->assertSee('East Legon Care')
            ->assertDontSee('West Hills Care')
            ->assertDontSee('name="branch_id"', false)
            ->assertDontSee('<select', false);

        $this->actingAs($doctor)
            ->get(route('care.patients.index'))
            ->assertOk()
            ->assertSee('Ama Mensah')
            ->assertDontSee('Kofi Boateng');
    }
}
