<?php

namespace App\Modules\HR\Employees\Requests;

use App\Modules\HR\Employees\Models\Employee;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class LinkEmployeeUserAccountRequest extends FormRequest
{
    public function authorize(): bool
    {
        $employee = $this->route('employee');

        return $employee instanceof Employee
            && ($this->user()?->can('employees.update', $employee) ?? false)
            && ($this->user()?->can('settings.users.assign_roles') ?? false);
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $tenantId = $this->user()?->tenant_id;

        return [
            'user_id' => [
                'required',
                'integer',
                Rule::exists('users', 'id')->where(function ($q) use ($tenantId): void {
                    $q->where('tenant_id', $tenantId)
                        ->where('is_admin', false)
                        ->whereNull('employee_id');
                }),
            ],
        ];
    }
}
