<?php

namespace App\Services\Care;

use App\Models\CareUnit;
use App\Models\Member;
use App\Models\Organization;
use App\Models\StaffAssignment;
use App\Models\User;
use Illuminate\Support\Collection;

class NursingServicesService
{
    /** @var list<string> */
    public const NURSING_ROLES = [
        'nurse',
        'ed_nurse',
        'theatre_nurse',
        'labour_ward_nurse',
        'fertility_nurse',
        'dialysis_nurse',
        'midwife',
    ];

    /**
     * @return Collection<int, Member>
     */
    public function nurseRegistry(Organization $organization, string $ownerRef): Collection
    {
        return Member::owned($ownerRef)
            ->where('organization_id', $organization->id)
            ->whereIn('role', self::NURSING_ROLES)
            ->with('branch')
            ->orderBy('role')
            ->get();
    }

    /**
     * Active placements for nursing staff today.
     *
     * @return Collection<int, StaffAssignment>
     */
    public function activeAllocations(Organization $organization, string $ownerRef): Collection
    {
        return StaffAssignment::owned($ownerRef)
            ->where('organization_id', $organization->id)
            ->where('status', 'active')
            ->unitPlacements()
            ->effectiveOn(now())
            ->whereHas('member', fn ($q) => $q->whereIn('role', self::NURSING_ROLES))
            ->with(['member', 'careUnit.department', 'department'])
            ->orderBy('care_unit_id')
            ->get();
    }

    /**
     * Care units useful for nursing ops (inpatient / outpatient / float / service).
     *
     * @return Collection<int, CareUnit>
     */
    public function careUnits(Organization $organization, string $ownerRef): Collection
    {
        return CareUnit::owned($ownerRef)
            ->where('organization_id', $organization->id)
            ->where('is_active', true)
            ->with('department.branch')
            ->orderBy('name')
            ->get();
    }

    /**
     * @param  Collection<int, Member>  $members
     * @return array<int, string>
     */
    public function memberLabels(Collection $members): array
    {
        return app(RosterService::class)->memberLabels($members);
    }
}
