<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
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 Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class CarePrescriptionTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

    protected Organization $organization;

    protected Consultation $consultation;

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

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

        $this->organization = Organization::create([
            'owner_ref' => $this->user->public_id,
            'name' => 'Test Clinic',
            'slug' => 'test-clinic',
            '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' => 'doctor',
        ]);

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

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

        $patient = 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' => 'LC-2026-00001',
            'first_name' => 'Kofi',
            'last_name' => 'Asante',
        ]);

        $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(),
        ]);

        $this->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(),
        ]);
    }

    public function test_doctor_can_create_prescription(): void
    {
        $this->actingAs($this->user)
            ->post(route('care.prescriptions.store', $this->consultation), [
                'activate' => true,
                'items' => [
                    [
                        'name' => 'Paracetamol 500mg',
                        'dosage' => '1 tablet',
                        'frequency' => 'TDS',
                        'duration' => '5 days',
                        'route' => 'oral',
                    ],
                    [
                        'is_procedure' => true,
                        'name' => 'Wound dressing',
                        'instructions' => 'Daily for 3 days',
                    ],
                ],
            ])
            ->assertRedirect();

        $prescription = Prescription::first();
        $this->assertNotNull($prescription);
        $this->assertSame(Prescription::STATUS_ACTIVE, $prescription->status);
        $this->assertSame(2, $prescription->items()->count());
        $this->assertDatabaseHas('care_audit_logs', ['action' => 'prescription.created']);
    }

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

        $prescription->items()->create([
            'owner_ref' => $this->user->public_id,
            'name' => 'Amoxicillin 500mg',
            'dosage' => '1 capsule',
            'frequency' => 'BD',
            'duration' => '7 days',
        ]);

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

        $this->actingAs($this->user)
            ->get(route('care.prescriptions.queue'))
            ->assertOk()
            ->assertSee('Amoxicillin 500mg');

        $this->actingAs($this->user)
            ->post(route('care.prescriptions.dispense', $prescription))
            ->assertRedirect(route('care.prescriptions.queue'));

        $prescription->refresh();
        $this->assertSame(Prescription::STATUS_DISPENSED, $prescription->status);
        $this->assertDatabaseHas('care_audit_logs', ['action' => 'prescription.dispensed']);
    }

    public function test_api_can_create_prescription(): void
    {
        Sanctum::actingAs($this->user);

        $this->postJson("/api/v1/consultations/{$this->consultation->uuid}/prescriptions", [
            'activate' => true,
            'items' => [
                ['name' => 'Ibuprofen 400mg', 'dosage' => '1 tablet', 'frequency' => 'PRN'],
            ],
        ])
            ->assertCreated()
            ->assertJsonPath('status', Prescription::STATUS_ACTIVE);
    }
}
