<?php

namespace Tests\Feature;

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

/**
 * Natural list UX: no bolted-on Service counter panels; Queue ops live on role lists when enabled.
 */
class CareNaturalQueueTest 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-owner',
            'name' => 'Owner',
            'email' => 'queue-owner@example.com',
        ]);

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

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

        Member::query()->where('user_ref', $this->owner->public_id)->update([
            'branch_id' => $this->branch->id,
        ]);
    }

    public function test_sidebar_does_not_show_service_queues_nav(): void
    {
        $this->actingAs($this->owner)
            ->get(route('care.dashboard'))
            ->assertOk()
            ->assertDontSee('Service queues', false);
    }

    public function test_service_queues_index_redirects_to_clinical_queue(): void
    {
        Member::query()->where('user_ref', $this->owner->public_id)->update(['role' => 'doctor']);

        $this->actingAs($this->owner)
            ->get(route('care.service-queues.index'))
            ->assertRedirect(route('care.queue.index'));
    }

    public function test_service_queues_redirect_cashiers_to_billing_not_appointments(): void
    {
        Member::query()->where('user_ref', $this->owner->public_id)->update(['role' => 'cashier']);

        $this->actingAs($this->owner)
            ->get(route('care.service-queues.index'))
            ->assertRedirect(route('care.bills.index'));
    }

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

        $this->actingAs($this->owner)
            ->get(route('care.service-queues.index'))
            ->assertRedirect(route('care.prescriptions.queue'));
    }

    public function test_clinical_queue_shows_inline_ops_not_service_counter(): void
    {
        Member::query()->where('user_ref', $this->owner->public_id)->update(['role' => 'doctor']);

        $this->actingAs($this->owner)
            ->get(route('care.queue.index'))
            ->assertOk()
            ->assertDontSee('Service counter')
            ->assertSee('Call next')
            ->assertSee('Patient flow')
            ->assertSee('Called')
            ->assertSee('Done');
    }

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

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

    public function test_lab_page_shows_call_next_when_integration_on(): void
    {
        Member::query()->where('user_ref', $this->owner->public_id)->update(['role' => 'lab_technician']);

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

    public function test_integration_off_hides_queue_controls(): void
    {
        Member::query()->where('user_ref', $this->owner->public_id)->update(['role' => 'doctor']);

        $settings = $this->organization->settings;
        $settings['queue_integration_enabled'] = false;
        $this->organization->update(['settings' => $settings]);

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

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

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

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

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

        $appointment = Appointment::create([
            '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(),
        ]);

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

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

        $this->assertDatabaseHas('care_queue_tickets', [
            'care_entity_id' => $appointment->id,
            'status' => CareQueueTicket::STATUS_CALLED,
        ]);
        $this->assertDatabaseMissing('care_service_queues', [
            'organization_id' => $this->organization->id,
            'context' => 'reception',
        ]);
        Http::assertNothingSent();
    }
}
