<?php

namespace App\Domains\Menu\Requests;

use App\Domains\Menu\Models\Menu;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;

class StoreTenantMenuRequest extends FormRequest
{
    private ?Menu $menuModel = null;

    public function authorize(): bool
    {
        return true;
    }

    protected function prepareForValidation(): void
    {
        $this->menuModel = Menu::query()
            ->where('code', $this->route('menu_code'))
            ->first();

        if (! $this->menuModel) {
            throw ValidationException::withMessages([
                'menu_code' => __('api.menu.not_found'),
            ]);
        }
    }

    public function rules(): array
    {
        if ($this->menuModel?->content_type !== Menu::CONTENT_TYPE_STATIC) {
            return [
                'static_content' => ['nullable', 'array'],
            ];
        }

        $rules = [
            'static_content' => ['required', 'array'],
        ];

        foreach ($this->menuModel->static_content_schema as $field => $rule) {
            $rules["static_content.{$field}"] = $rule;
        }

        return $rules;
    }
}
