<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Bed;
use App\Models\Branch;
use App\Models\CareUnit;
use App\Models\Department;
use App\Models\Member;
use App\Models\Organization;
use App\Models\StaffAssignment;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CareStaffManagementTest extends TestCase
{
    use RefreshDatabase;

    protected User $owner;

    protected Organization $organization;

    protected Branch $branch;

    protected Department $department;

    protected Member $adminMember;

    protected Member $nurseMember;

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

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

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

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

        $nurse = User::create([
            'public_id' => 'staff-nurse-ama',
            'name' => 'Nurse Ama',
            'email' => 'ama@example.com',
        ]);

        $this->nurseMember = Member::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'user_ref' => $nurse->public_id,
            'role' => 'midwife',
            'branch_id' => $this->branch->id,
        ]);
    }

    public function test_create_inpatient_unit_and_bed(): void
    {
        $this->actingAs($this->owner)
            ->post(route('care.care-units.store'), [
                'department_id' => $this->department->id,
                'name' => 'Postnatal Ward',
                'code' => 'PN',
                'kind' => 'inpatient',
            ])
            ->assertRedirect();

        $unit = CareUnit::query()->where('name', 'Postnatal Ward')->first();
        $this->assertNotNull($unit);
        $this->assertTrue($unit->supportsBeds());

        $this->actingAs($this->owner)
            ->post(route('care.care-units.beds.store', $unit), [
                'label' => 'PN-01',
                'room' => 'A',
                'status' => 'available',
            ])
            ->assertRedirect(route('care.care-units.show', $unit));

        $this->assertDatabaseHas('care_beds', [
            'care_unit_id' => $unit->id,
            'label' => 'PN-01',
            'status' => 'available',
        ]);
    }

    public function test_outpatient_unit_rejects_beds(): void
    {
        $unit = CareUnit::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'department_id' => $this->department->id,
            'name' => 'ANC Clinic',
            'kind' => 'outpatient',
            'is_active' => true,
        ]);

        $this->actingAs($this->owner)
            ->post(route('care.care-units.beds.store', $unit), [
                'label' => 'X-1',
                'status' => 'available',
            ])
            ->assertStatus(422);

        $this->assertSame(0, Bed::query()->where('care_unit_id', $unit->id)->count());
    }

    public function test_primary_and_temporary_assignments(): void
    {
        $floatDept = Department::create([
            'owner_ref' => $this->owner->public_id,
            'branch_id' => $this->branch->id,
            'name' => 'Nursing Services',
            'type' => 'nursing',
            'is_active' => true,
        ]);

        $floatPool = CareUnit::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'department_id' => $floatDept->id,
            'name' => 'Float Pool',
            'kind' => 'float_pool',
            'is_active' => true,
        ]);

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

        $this->actingAs($this->owner)
            ->post(route('care.staff-assignments.store'), [
                'member_id' => $this->nurseMember->id,
                'department_id' => $floatDept->id,
                'care_unit_id' => $floatPool->id,
                'kind' => 'primary',
                'assignment_role' => 'float_nurse',
                'starts_on' => now()->toDateString(),
                'status' => 'active',
            ])
            ->assertRedirect(route('care.staff-assignments.index'));

        $this->actingAs($this->owner)
            ->post(route('care.staff-assignments.store'), [
                'member_id' => $this->nurseMember->id,
                'department_id' => $this->department->id,
                'care_unit_id' => $labour->id,
                'kind' => 'temporary',
                'assignment_role' => 'midwife',
                'starts_on' => now()->toDateString(),
                'ends_on' => now()->toDateString(),
                'status' => 'active',
                'notes' => 'Covering labour tonight',
            ])
            ->assertRedirect(route('care.staff-assignments.index'));

        $this->assertSame(2, StaffAssignment::query()->where('member_id', $this->nurseMember->id)->count());

        $effective = StaffAssignment::query()
            ->where('member_id', $this->nurseMember->id)
            ->activeStatus()
            ->effectiveOn(now())
            ->count();
        $this->assertSame(2, $effective);

        $this->actingAs($this->owner)
            ->get(route('care.staff-assignments.index'))
            ->assertOk()
            ->assertSee('Unit assignments')
            ->assertSee('Float Pool')
            ->assertSee('Labour Ward')
            ->assertDontSee('>Shift<', false);
    }

    public function test_temporary_assignment_requires_unit(): void
    {
        $this->actingAs($this->owner)
            ->from(route('care.staff-assignments.create'))
            ->post(route('care.staff-assignments.store'), [
                'member_id' => $this->nurseMember->id,
                'kind' => 'temporary',
                'starts_on' => now()->toDateString(),
                'status' => 'active',
            ])
            ->assertRedirect(route('care.staff-assignments.create'))
            ->assertSessionHasErrors('care_unit_id');
    }

    public function test_care_units_index_lists_units(): void
    {
        CareUnit::create([
            'owner_ref' => $this->owner->public_id,
            'organization_id' => $this->organization->id,
            'department_id' => $this->department->id,
            'name' => 'ANC Clinic',
            'kind' => 'outpatient',
            'is_active' => true,
        ]);

        $this->actingAs($this->owner)
            ->get(route('care.care-units.index'))
            ->assertOk()
            ->assertSee('ANC Clinic')
            ->assertSee('Outpatient');
    }
}
