<?php

namespace App\Modules\HR\Employees\Requests;

use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Customization\CustomFields\Services\CustomFieldRendererService;
use App\Modules\HR\Departments\Models\Department;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator as ValidatorFacade;
use Illuminate\Validation\Validator;

class StoreEmployeeRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('employees.create') ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $docs = Gate::allows('employees.documents.view') ? EmployeeFormRules::documents() : [];

        return array_merge(
            EmployeeFormRules::employeeCore(Gate::allows('employees.salary.view')),
            EmployeeFormRules::address(),
            $docs,
            EmployeeFormRules::customFieldsShell(),
        );
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            EmployeeRequestValidator::after($validator, $this, null);
        });

        $validator->after(function (Validator $validator): void {
            if ($validator->errors()->isNotEmpty()) {
                return;
            }
            $dept = Department::query()->find((int) $this->input('department_id'));
            if ($dept === null) {
                return;
            }
            $tenant = Tenant::query()->find((int) $dept->tenant_id);
            $rules = app(CustomFieldRendererService::class)->validationRules($tenant, 'hr', 'employees');
            $inner = ValidatorFacade::make($this->all(), $rules);
            if ($inner->fails()) {
                $validator->errors()->merge($inner->errors());
            }
        });
    }
}
