<?php

namespace App\Http\Requests\Leave;

use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class UpdateLeaveTypeAssignmentsRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $companyId = Auth::user()?->company_id;

        $deptExists = Rule::exists('departments', 'id');
        $roleExists = Rule::exists('roles', 'id');
        $userExists = Rule::exists('users', 'id')->where(function ($q) {
            $q->where('user_type', User::USER_TYPE_STAFF);
        });

        if ($companyId) {
            $deptExists = $deptExists->where(fn ($q) => $q->where('company_id', $companyId));
            $roleExists = $roleExists->where(fn ($q) => $q->where('company_id', $companyId));
            $userExists = $userExists->where(fn ($q) => $q->where('company_id', $companyId));
        }

        return [
            'apply_to_all' => ['nullable', 'boolean'],
            'department_ids' => ['nullable', 'array'],
            'department_ids.*' => ['integer', $deptExists],
            'role_ids' => ['nullable', 'array'],
            'role_ids.*' => ['integer', $roleExists],
            'user_ids' => ['nullable', 'array'],
            'user_ids.*' => ['integer', $userExists],
        ];
    }
}

