<?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'],
        ];
    }

    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'));
            }
        });
    }
}
