<?php

namespace App\Http\Requests\Authz;

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

class RolePermissionGrantRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'permission_names' => 'sometimes|array',
            'permission_names.*' => 'string|min:1',
            'menus' => 'sometimes|array',
            'menus.*' => 'integer|min:1',
            'actions' => 'sometimes|array',
            'actions.*' => [
                'string', Rule::in(config('authz.menu_actions', ['view', 'create', 'update', 'delete', 'approve'])),
            ],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $data = $this->all();
            if (empty($data['permission_names']) && (empty($data['menus']) || empty($data['actions']))) {
                $validator->errors()->add('permission_names', __('error.role.permission_input_required'));
            }
        });
    }
}
