<?php

namespace App\Modules\HR\Positions\Requests;

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

class UpdatePositionRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('positions.update', $this->route('position')) ?? 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'],
            'is_active' => ['required', 'boolean'],
        ];
    }

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

    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();
            $position = $this->route('position');
            if ($position instanceof Position && (int) $dept->tenant_id !== (int) $position->tenant_id) {
                $validator->errors()->add('department_id', __('positions.validation.department_position_tenant'));
            }
            if ($user !== null && ! $user->isAdmin() && (int) $dept->tenant_id !== (int) $user->tenant_id) {
                $validator->errors()->add('department_id', __('positions.validation.department_tenant'));
            }
        });
    }
}
