<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Bed;
use App\Models\BedStay;
use App\Models\Branch;
use App\Models\CareUnit;
use App\Models\Department;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\User;
use App\Models\Visit;
use App\Services\Care\VisitService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CareVisitPlacementTest extends TestCase
{
    use RefreshDatabase;

    protected User $owner;

    protected Organization $organization;

    protected Branch $branch;

    protected Department $department;

    protected CareUnit $unit;

    protected Bed $bed;

    protected Visit $visit;

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

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

        $this->organization = Organization::create([
            'owner_ref' => $this->owner->public_id,
            'name' => 'Placement Hospital',
            'slug' => 'placement-hospital',
            'settings' => [
                'onboarded' => true,
                'facility_type' => 'hospital',
                'plan' => 'pro',
                'plan_expires_at' => now()->addMonth()->toIso8601String(),
            ],
        ]);

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

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

        $this->department = Department::create([
            'owner_ref' => $this->owner->public_id,
            'branch_id' => $this->branch->id,
            'name' => "Women's Health",
            'type' => 'womens_health',
            'is_active' => true,
        ]);

        $this->unit = CareUnit::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'department_id' => $this->department->id,
            'name' => 'Postnatal Ward',
            'kind' => 'inpatient',
            'is_active' => true,
        ]);

        $this->bed = Bed::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'care_unit_id' => $this->unit->id,
            'label' => 'PN-01',
            'status' => 'available',
            '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-PLACE-1',
            'first_name' => 'Ama',
            'last_name' => 'Mensah',
            'gender' => 'female',
        ]);

        $this->visit = Visit::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_id' => $patient->id,
            'status' => Visit::STATUS_OPEN,
            'checked_in_at' => now(),
        ]);
    }

    public function test_place_visit_occupies_bed(): void
    {
        $this->actingAs($this->owner)
            ->post(route('care.care-units.placements.store', $this->unit), [
                'visit_id' => $this->visit->id,
                'bed_id' => $this->bed->id,
            ])
            ->assertRedirect(route('care.care-units.show', $this->unit));

        $this->visit->refresh();
        $this->bed->refresh();

        $this->assertSame($this->unit->id, $this->visit->care_unit_id);
        $this->assertSame($this->bed->id, $this->visit->bed_id);
        $this->assertSame('occupied', $this->bed->status);
        $this->assertDatabaseHas('care_bed_stays', [
            'visit_id' => $this->visit->id,
            'bed_id' => $this->bed->id,
            'status' => BedStay::STATUS_ACTIVE,
            'reason' => 'admit',
        ]);
    }

    public function test_transfer_frees_old_bed_and_occupies_new(): void
    {
        $otherUnit = CareUnit::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'department_id' => $this->department->id,
            'name' => 'Labour Ward',
            'kind' => 'inpatient',
            'is_active' => true,
        ]);
        $otherBed = Bed::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'care_unit_id' => $otherUnit->id,
            'label' => 'LW-02',
            'status' => 'available',
            'is_active' => true,
        ]);

        $this->actingAs($this->owner)
            ->post(route('care.care-units.placements.store', $this->unit), [
                'visit_id' => $this->visit->id,
                'bed_id' => $this->bed->id,
            ])
            ->assertRedirect();

        $this->actingAs($this->owner)
            ->post(route('care.visits.placement.transfer', $this->visit), [
                'care_unit_id' => $otherUnit->id,
                'bed_id' => $otherBed->id,
            ])
            ->assertRedirect(route('care.care-units.show', $otherUnit));

        $this->visit->refresh();
        $this->bed->refresh();
        $otherBed->refresh();

        $this->assertSame($otherUnit->id, $this->visit->care_unit_id);
        $this->assertSame($otherBed->id, $this->visit->bed_id);
        $this->assertSame('available', $this->bed->status);
        $this->assertSame('occupied', $otherBed->status);
        $this->assertSame(1, BedStay::query()->where('visit_id', $this->visit->id)->active()->count());
    }

    public function test_discharge_placement_frees_bed(): void
    {
        $this->actingAs($this->owner)
            ->post(route('care.care-units.placements.store', $this->unit), [
                'visit_id' => $this->visit->id,
                'bed_id' => $this->bed->id,
            ]);

        $this->actingAs($this->owner)
            ->delete(route('care.visits.placement.destroy', $this->visit))
            ->assertRedirect();

        $this->visit->refresh();
        $this->bed->refresh();

        $this->assertNull($this->visit->care_unit_id);
        $this->assertNull($this->visit->bed_id);
        $this->assertSame('available', $this->bed->status);
    }

    public function test_completing_visit_discharges_placement(): void
    {
        $this->actingAs($this->owner)
            ->post(route('care.care-units.placements.store', $this->unit), [
                'visit_id' => $this->visit->id,
                'bed_id' => $this->bed->id,
            ]);

        app(VisitService::class)->complete($this->visit, $this->owner->public_id, $this->owner->public_id);

        $this->visit->refresh();
        $this->bed->refresh();

        $this->assertSame(Visit::STATUS_COMPLETED, $this->visit->status);
        $this->assertNull($this->visit->care_unit_id);
        $this->assertSame('available', $this->bed->status);
    }

    public function test_cannot_place_on_float_pool(): void
    {
        $float = CareUnit::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'department_id' => $this->department->id,
            'name' => 'Float Pool',
            'kind' => 'float_pool',
            'is_active' => true,
        ]);

        $this->actingAs($this->owner)
            ->from(route('care.care-units.show', $float))
            ->post(route('care.care-units.placements.store', $float), [
                'visit_id' => $this->visit->id,
            ])
            ->assertRedirect()
            ->assertSessionHasErrors('care_unit_id');
    }

    public function test_second_patient_cannot_take_occupied_bed(): void
    {
        $this->actingAs($this->owner)
            ->post(route('care.care-units.placements.store', $this->unit), [
                'visit_id' => $this->visit->id,
                'bed_id' => $this->bed->id,
            ]);

        $otherPatient = Patient::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_number' => 'P-PLACE-2',
            'first_name' => 'Kwame',
            'last_name' => 'Boateng',
            'gender' => 'male',
        ]);
        $otherVisit = Visit::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_id' => $otherPatient->id,
            'status' => Visit::STATUS_OPEN,
            'checked_in_at' => now(),
        ]);

        $this->actingAs($this->owner)
            ->from(route('care.care-units.show', $this->unit))
            ->post(route('care.care-units.placements.store', $this->unit), [
                'visit_id' => $otherVisit->id,
                'bed_id' => $this->bed->id,
            ])
            ->assertRedirect()
            ->assertSessionHasErrors('bed_id');
    }
}
