<?php

namespace App\Domains\Catalog\Requests;

use App\Domains\Shared\Enums\FieldType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

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

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'codigo' => [
                'required',
                'string',
                'max:255',
                Rule::unique('attribute', 'codigo')->where(
                    fn ($query) => $query->where('tenant_codigo', $this->route('tenant')?->codigo)
                ),
            ],
            'nombre' => ['required', 'string', 'max:255'],
            'is_required' => ['sometimes', 'boolean'],
            'metadata_schema' => ['nullable', 'array'],
            'type' => ['required', Rule::enum(FieldType::class)],
            'options' => [
                Rule::requiredIf(fn (): bool => in_array($this->input('type'), [
                    FieldType::Select->value,
                    FieldType::Multiselect->value,
                ], true)),
                Rule::prohibitedIf(fn (): bool => ! in_array($this->input('type'), [
                    FieldType::Select->value,
                    FieldType::Multiselect->value,
                ], true)),
                'array',
            ],
            'options.*.value' => ['required', 'string', 'max:255'],
            'options.*.label' => ['required', 'string', 'max:255'],
            'options.*.sort_order' => ['sometimes', 'integer'],
            'options.*.metadata' => ['nullable', 'array'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            $type = $this->input('type');
            $supportsOptions = in_array($type, [FieldType::Select->value, FieldType::Multiselect->value], true);

            if (! $supportsOptions && $this->filled('metadata_schema')) {
                $validator->errors()->add('metadata_schema', 'The metadata_schema field is only allowed for select and multiselect attributes.');
            }

            if (! $supportsOptions && $this->filled('options')) {
                $validator->errors()->add('options', 'Options are only allowed for select and multiselect attributes.');
            }
        });
    }
}
