<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Branch;
use App\Models\Consultation;
use App\Models\Department;
use App\Models\DispensingRecord;
use App\Models\Drug;
use App\Models\DrugBatch;
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 Tests\TestCase;

class CarePharmacyInventoryTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

    protected Organization $organization;

    protected Prescription $prescription;

    protected \App\Models\PrescriptionItem $prescriptionItem;

    protected Drug $drug;

    protected DrugBatch $batch;

    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' => 'pharmacist',
        ]);

        $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' => 'Ama',
            'last_name' => 'Mensah',
        ]);

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

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

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

        $this->drug = Drug::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'name' => 'Amoxicillin 500mg',
            'unit' => 'capsule',
            'unit_price_minor' => 1500,
            'reorder_level' => 10,
            'is_active' => true,
        ]);

        $this->batch = DrugBatch::create([
            'owner_ref' => $this->user->public_id,
            'drug_id' => $this->drug->id,
            'batch_number' => 'AMX-001',
            'expiry_date' => now()->addYear()->toDateString(),
            'quantity_on_hand' => 50,
            'cost_minor' => 1000,
            'received_at' => now(),
        ]);
    }

    public function test_pharmacist_can_manage_drug_inventory(): void
    {
        $this->actingAs($this->user)
            ->get(route('care.pharmacy.drugs.index'))
            ->assertOk()
            ->assertSee('Amoxicillin 500mg');

        $this->actingAs($this->user)
            ->get(route('care.pharmacy.drugs.show', $this->drug))
            ->assertOk()
            ->assertSee('AMX-001');

        $this->actingAs($this->user)
            ->post(route('care.pharmacy.drugs.batches.store', $this->drug), [
                'batch_number' => 'AMX-002',
                'expiry_date' => now()->addMonths(6)->toDateString(),
                'quantity_on_hand' => 20,
                'cost_minor' => 1100,
            ])
            ->assertRedirect();

        $this->assertDatabaseHas('care_drug_batches', ['batch_number' => 'AMX-002']);
        $this->assertDatabaseHas('care_audit_logs', ['action' => 'drug.batch_received']);
    }

    public function test_dispense_with_stock_deducts_batch_quantity(): void
    {
        $this->actingAs($this->user)
            ->post(route('care.prescriptions.dispense', $this->prescription), [
                'allocations' => [
                    [
                        'prescription_item_id' => $this->prescriptionItem->id,
                        'drug_batch_id' => $this->batch->id,
                        'quantity' => 14,
                    ],
                ],
            ])
            ->assertRedirect(route('care.prescriptions.queue'));

        $this->batch->refresh();
        $this->prescription->refresh();

        $this->assertSame(36, $this->batch->quantity_on_hand);
        $this->assertSame(Prescription::STATUS_DISPENSED, $this->prescription->status);
        $this->assertSame(1, DispensingRecord::count());
        $this->assertDatabaseHas('care_audit_logs', ['action' => 'prescription.dispensed']);
    }
}
