<?php

namespace App\Modules\Settings\Rbac\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class InviteTenantUserRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('settings.users.invite') ?? false;
    }

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

        return [
            'name' => ['required', 'string', 'max:191'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:191', Rule::unique('users', 'email')],
            'employee_id' => [
                'nullable',
                'integer',
                Rule::exists('employees', 'id')->where(
                    fn ($q) => $q->where('tenant_id', $tenantId),
                ),
                Rule::unique('users', 'employee_id'),
            ],
            'role_ids' => ['required', 'array', 'min:1'],
            'role_ids.*' => [
                'integer',
                'distinct',
                Rule::exists('roles', 'id')->where(
                    fn ($q) => $q->where('tenant_id', $tenantId)
                        ->where('is_active', true)
                        ->whereNull('deleted_at'),
                ),
            ],
        ];
    }
}
