<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Appointment;
use App\Models\Branch;
use App\Models\CareQueueTicket;
use App\Models\CareServiceQueue;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\User;
use App\Services\Care\AppointmentService;
use App\Services\Care\CareQueueBridge;
use App\Services\Care\CareQueueContexts;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Tests\TestCase;

class CareQueueWorkflowTest extends TestCase
{
    use RefreshDatabase;

    protected User $owner;

    protected Organization $organization;

    protected Branch $branch;

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

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

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

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

    public function test_integration_off_does_not_issue_tickets_on_check_in(): void
    {
        $settings = $this->organization->settings;
        $settings['queue_integration_enabled'] = false;
        $this->organization->update(['settings' => $settings]);

        Http::fake();

        $patient = Patient::create([
            'uuid' => (string) Str::uuid(),
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_number' => 'P-1',
            'first_name' => 'Ada',
            'last_name' => 'Lovelace',
        ]);

        $appointment = Appointment::create([
            'uuid' => (string) Str::uuid(),
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_id' => $patient->id,
            'type' => Appointment::TYPE_SCHEDULED,
            'status' => Appointment::STATUS_SCHEDULED,
            'scheduled_at' => now(),
        ]);

        app(AppointmentService::class)->checkIn($appointment, $this->owner->public_id, $this->owner->public_id);

        $appointment->refresh();
        $this->assertNull($appointment->queue_ticket_uuid);
        $this->assertNull($appointment->queue_ticket_number);
        Http::assertNothingSent();
    }

    public function test_integration_on_issues_consultation_ticket_on_check_in(): void
    {
        Http::fake();

        $practitioner = \App\Models\Practitioner::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'name' => 'Dr. Workflow',
            'room' => 'Room 2',
            'is_active' => true,
        ]);

        $patient = Patient::create([
            'uuid' => (string) Str::uuid(),
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_number' => 'P-2',
            'first_name' => 'Grace',
            'last_name' => 'Hopper',
        ]);

        $appointment = Appointment::create([
            'uuid' => (string) Str::uuid(),
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_id' => $patient->id,
            'practitioner_id' => $practitioner->id,
            'type' => Appointment::TYPE_SCHEDULED,
            'status' => Appointment::STATUS_SCHEDULED,
            'scheduled_at' => now(),
        ]);

        app(AppointmentService::class)->checkIn($appointment, $this->owner->public_id, $this->owner->public_id);

        $appointment->refresh();
        $this->assertNotNull($appointment->queue_ticket_uuid);
        $this->assertSame('C001', $appointment->queue_ticket_number);
        $this->assertSame('waiting', $appointment->queue_ticket_status);
        $this->assertDatabaseHas('care_queue_tickets', [
            'uuid' => $appointment->queue_ticket_uuid,
            'ticket_number' => 'C001',
            'status' => CareQueueTicket::STATUS_WAITING,
        ]);
        $this->assertDatabaseHas('care_service_queues', [
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'context' => CareQueueContexts::CONSULTATION,
        ]);
        Http::assertNothingSent();
    }

    public function test_pharmacy_call_next_uses_pharmacy_queue_not_reception(): void
    {
        Http::fake();

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

        Member::query()->where('user_ref', $this->owner->public_id)->update(['role' => 'pharmacist']);

        $queue = CareServiceQueue::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'context' => CareQueueContexts::PHARMACY,
            'name' => 'Pharmacy',
            'prefix' => 'P',
            'routing_mode' => 'assigned_only',
            'external_key' => CareQueueContexts::queueExternalKey(CareQueueContexts::PHARMACY, $this->branch->id),
        ]);

        $point = $queue->points()->create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'name' => 'Pharmacy counter 1',
            'destination' => 'Pharmacy counter 1',
            'kind' => 'member',
            'ref_id' => $pharmacist->id,
            'staff_ref' => 'pharm-workflow',
            'external_key' => CareQueueContexts::pointExternalKey(
                CareQueueContexts::PHARMACY,
                $this->branch->id,
                'member',
                $pharmacist->id,
            ),
        ]);

        $settings = $this->organization->settings;
        $settings['department_queue_provisioning'] = [
            CareQueueContexts::PHARMACY => [
                'queues' => [[
                    'branch_id' => $this->branch->id,
                    'branch_name' => 'Main',
                    'name' => 'Pharmacy',
                    'prefix' => 'P',
                    'active' => true,
                    'synced' => true,
                    'routing_mode' => 'assigned_only',
                    'queue_uuid' => $queue->uuid,
                    'counter_uuid' => $point->uuid,
                    'queue_external_key' => $queue->external_key,
                    'points' => [[
                        'kind' => 'member',
                        'ref_id' => $pharmacist->id,
                        'staff_ref' => 'pharm-workflow',
                        'destination' => 'Pharmacy counter 1',
                        'counter_uuid' => $point->uuid,
                        'external_key' => $point->external_key,
                        'synced' => true,
                    ]],
                ]],
            ],
        ];
        $this->organization->update(['settings' => $settings]);

        CareQueueTicket::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'service_queue_id' => $queue->id,
            'service_point_id' => $point->id,
            'ticket_number' => 'P001',
            'status' => CareQueueTicket::STATUS_WAITING,
            'priority' => 'walk_in',
            'customer_name' => 'Pharmacy Patient',
        ]);

        $this->actingAs($this->owner)
            ->post(route('care.prescriptions.call-next'), ['branch_id' => $this->branch->id])
            ->assertRedirect();

        $this->assertDatabaseHas('care_queue_tickets', [
            'ticket_number' => 'P001',
            'status' => CareQueueTicket::STATUS_CALLED,
            'service_queue_id' => $queue->id,
        ]);
        Http::assertNothingSent();
    }

    public function test_complete_advances_ticket_status_on_appointment(): void
    {
        Http::fake();

        $practitioner = \App\Models\Practitioner::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'name' => 'Dr. Complete',
            'room' => 'Room 1',
            'is_active' => true,
        ]);

        $patient = Patient::create([
            'uuid' => (string) Str::uuid(),
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_number' => 'P-3',
            'first_name' => 'Alan',
            'last_name' => 'Turing',
        ]);

        $appointment = Appointment::create([
            'uuid' => (string) Str::uuid(),
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_id' => $patient->id,
            'practitioner_id' => $practitioner->id,
            'type' => Appointment::TYPE_WALK_IN,
            'status' => Appointment::STATUS_SCHEDULED,
            'scheduled_at' => now(),
        ]);

        $appointment = app(AppointmentService::class)->checkIn(
            $appointment->fresh(['organization', 'patient', 'practitioner']),
            $this->owner->public_id,
            $this->owner->public_id,
        );

        $bridge = app(CareQueueBridge::class);
        $bridge->callNext(
            $this->organization->fresh(),
            CareQueueContexts::CONSULTATION,
            (int) $this->branch->id,
            null,
            $practitioner->id,
        );
        $bridge->serve($this->organization->fresh(), $appointment->fresh());
        $bridge->complete($this->organization->fresh(), $appointment->fresh());

        $appointment->refresh();
        $this->assertSame('completed', $appointment->queue_ticket_status);
        $this->assertDatabaseHas('care_queue_tickets', [
            'uuid' => $appointment->queue_ticket_uuid,
            'status' => CareQueueTicket::STATUS_COMPLETED,
        ]);
        Http::assertNothingSent();
    }

    public function test_patient_queue_shows_call_next_not_service_counter_panel(): void
    {
        Http::fake();

        // Patient queue is reserved for clinical staff; receptionists are 403'd.
        Member::query()->where('user_ref', $this->owner->public_id)->update([
            'role' => 'doctor',
            'branch_id' => $this->branch->id,
        ]);

        $this->actingAs($this->owner)
            ->get(route('care.queue.index'))
            ->assertOk()
            ->assertDontSee('Service counter')
            ->assertSee('Call next');
        Http::assertNothingSent();
    }

    public function test_integration_off_hides_queue_ops_on_pharmacy_page(): void
    {
        $settings = $this->organization->settings;
        $settings['queue_integration_enabled'] = false;
        $this->organization->update(['settings' => $settings]);

        Member::query()->where('user_ref', $this->owner->public_id)->update(['role' => 'pharmacist']);

        $this->actingAs($this->owner)
            ->get(route('care.prescriptions.queue'))
            ->assertOk()
            ->assertDontSee('Call next')
            ->assertDontSee('Service counter');
    }
}
