<?php

namespace App\Modules\HR\Positions\Requests;

use App\Modules\HR\Departments\Models\Department;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

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

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:200'],
            'department_id' => ['required', 'integer', 'exists:departments,id'],
            'salary' => ['required', 'numeric', 'min:0', 'max:9999999999999.99'],
            'description' => ['nullable', 'string', 'max:5000'],
            'job_grade_id' => ['nullable', 'integer', 'exists:hr_job_grades,id'],
            'responsibilities' => ['nullable', 'string', 'max:10000'],
            'required_skills' => ['nullable', 'string', 'max:10000'],
            'min_salary' => ['nullable', 'numeric', 'min:0', 'lte:max_salary'],
            'max_salary' => ['nullable', 'numeric', 'min:0'],
            'kpis' => ['nullable', 'string', 'max:10000'],
            'required_training' => ['nullable', 'string', 'max:10000'],
            'career_path' => ['nullable', 'string', 'max:10000'],
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->input('description') === '') {
            $this->merge(['description' => null]);
        }
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            if ($validator->errors()->isNotEmpty()) {
                return;
            }
            $deptId = (int) $this->input('department_id');
            $dept = Department::query()->find($deptId);
            if ($dept === null) {
                return;
            }
            $user = $this->user();
            if ($user !== null && $user->isAdmin()) {
                return;
            }
            if ($user !== null && (int) $dept->tenant_id !== (int) $user->tenant_id) {
                $validator->errors()->add('department_id', __('positions.validation.department_tenant'));
            }
        });
    }
}
