<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Departments\Repositories\DepartmentRepository;
use App\Modules\HR\Employees\Services\EmployeeService;
use App\Modules\HR\EmploymentStatuses\Repositories\EmploymentStatusRepository;
use App\Modules\HR\EmploymentStatuses\Services\EmploymentStatusBootstrapService;
use App\Modules\HR\Positions\Repositories\PositionRepository;
use App\Modules\HR\Recruitment\Models\RecruitmentOfferLetter;
use App\Modules\HR\Recruitment\Repositories\RecruitmentHiringRepository;
use App\Modules\Settings\Rbac\Repositories\RoleRepository;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class HiringWizardPageService
{
    public function __construct(
        private readonly RecruitmentHiringRepository $hirings,
        private readonly HiringEmployeePrefillService $prefill,
        private readonly DepartmentRepository $departments,
        private readonly PositionRepository $positions,
        private readonly EmploymentStatusRepository $employmentStatuses,
        private readonly EmploymentStatusBootstrapService $employmentBootstrap,
        private readonly EmployeeService $employees,
        private readonly RoleRepository $roles,
    ) {}

    /** @param  array{q?: ?string}  $filters */
    public function paginateAccepted(array $filters = [], int $perPage = 20): LengthAwarePaginator
    {
        $tenantId = (int) (auth()->user()?->tenant_id ?? 0);
        abort_if($tenantId < 1, 403);

        return $this->hirings->paginateAcceptedOffers($tenantId, $filters, $perPage);
    }

    /** @return array<string, mixed> */
    public function wizardContext(RecruitmentOfferLetter $offer): array
    {
        $tenant = auth()->user()?->tenant;
        abort_if($tenant === null, 403);
        $this->employmentBootstrap->ensureDefaults($tenant);
        $offer->load(['candidate', 'vacancy', 'department', 'position', 'application', 'employmentStatus']);
        $defaultRoles = $this->roles->findBySlug((int) $tenant->id, 'employee');

        return [
            'offer' => $offer,
            'prefill' => $this->prefill->fromOffer($offer),
            'departmentOptions' => $this->departments->listForSelect(),
            'positionOptions' => $this->positions->listForSelect(),
            'managerOptions' => $this->employees->managerOptionsForForm((int) $tenant->id),
            'employmentStatusOptions' => $this->employmentStatuses->listForSelect(),
            'roles' => $this->roles->activeForTenant((int) $tenant->id),
            'defaultRoleIds' => $defaultRoles !== null ? [(int) $defaultRoles->id] : [],
            'canCreateUser' => auth()->user()?->can('settings.users.invite') ?? false,
        ];
    }
}
