<?php

namespace App\Modules\HR\Recruitment\Requests;

use App\Modules\HR\Employees\Requests\EmployeeFormRules;
use App\Modules\HR\Recruitment\Models\RecruitmentOfferLetter;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;

class CompleteHiringWizardRequest extends FormRequest
{
    public function authorize(): bool
    {
        $offer = $this->route('offer_letter');

        return $offer instanceof RecruitmentOfferLetter
            && ($this->user()?->can('hire', $offer) ?? false);
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'create_user_account' => $this->boolean('create_user_account'),
            'create_employment_contract' => $this->boolean('create_employment_contract', true),
        ]);
    }

    /** @return array<string, mixed> */
    public function rules(): array
    {
        $tenantId = $this->user()?->tenant_id;
        $createUser = $this->boolean('create_user_account');

        return array_merge(EmployeeFormRules::employeeCore(true), [
            'create_user_account' => ['sometimes', 'boolean'],
            'create_employment_contract' => ['sometimes', 'boolean'],
            'notes' => ['nullable', 'string', 'max:2000'],
            'password' => [$createUser ? 'required' : 'nullable', 'confirmed', Password::defaults()],
            'role_ids' => [$createUser ? 'required' : 'nullable', 'array', 'min:1'],
            'role_ids.*' => [
                'integer',
                'distinct',
                Rule::exists('roles', 'id')->where(
                    fn ($q) => $q->where('tenant_id', $tenantId)
                        ->where('is_active', true)
                        ->whereNull('deleted_at'),
                ),
            ],
        ]);
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($v): void {
            if (! $this->boolean('create_user_account')) {
                return;
            }
            if (! ($this->user()?->can('settings.users.invite') ?? false)) {
                $v->errors()->add('create_user_account', __('recruitment.hiring.errors.user_invite_forbidden'));
            }
            if (trim((string) $this->input('email', '')) === '') {
                $v->errors()->add('email', __('employees.user_account.validation.email_required'));
            }
        });
    }
}
