<?php

namespace App\Services\Hr;

use App\Models\User;
use Illuminate\Support\Collection;

class OffboardingAssigneeResolver
{
    /**
     * Pick the first suitable assignee for a checklist category.
     */
    public function resolveAssigneeId(int $companyId, string $category, ?User $exitingEmployee = null): ?int
    {
        $candidates = $this->resolveAssignees($companyId, $category, $exitingEmployee);

        return $candidates->first()?->id;
    }

    /**
     * @return Collection<int, User>
     */
    public function resolveAssignees(int $companyId, string $category, ?User $exitingEmployee = null): Collection
    {
        $permissions = match ($category) {
            'manager' => [],
            'it' => ['hr_operations_view'],
            'hr' => ['hr_operations_view'],
            'finance' => ['finance_operational', 'finance_view', 'finance_edit'],
            'assets' => ['assets_edit', 'assets_view'],
            'docs' => ['hr_operations_view'],
            default => ['hr_operations_view'],
        };

        if ($category === 'manager' && $exitingEmployee?->report_to) {
            $manager = User::withoutGlobalScopes()->find($exitingEmployee->report_to);
            if ($manager && (int) $manager->company_id === $companyId) {
                return collect([$manager]);
            }
        }

        if ($permissions === []) {
            return collect();
        }

        return User::withoutGlobalScopes()
            ->where('company_id', $companyId)
            ->where('is_superadmin', false)
            ->where('status', User::STATUS_ACTIVE)
            ->when($exitingEmployee, fn ($q) => $q->where('id', '!=', $exitingEmployee->id))
            ->whereHas('role.permissions', fn ($q) => $q->whereIn('name', $permissions))
            ->orderBy('name')
            ->get();
    }
}
