<?php

namespace App\Domains\FiestaFutbolInfantil\Requests;

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

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

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

        return [
            'items' => ['required', 'array', 'min:1', 'max:100'],
            'items.*' => ['required', 'array:id,title,description,max_units_per_user,variants'],
            'items.*.id' => [
                'sometimes',
                'nullable',
                'integer',
                'distinct',
                Rule::exists('catalog_items', 'id')->where(
                    fn ($query) => $query
                        ->where('tenant_code', $tenantCode)
                        ->whereIn('category_id', fn ($categoryQuery) => $categoryQuery
                            ->select('id')
                            ->from('categorias')
                            ->where('tenant_code', $tenantCode)
                            ->where('nombre', 'Merchandising'))
                ),
            ],
            'items.*.title' => ['required', 'string', 'max:255'],
            'items.*.description' => ['sometimes', 'nullable', 'string'],
            'items.*.max_units_per_user' => ['required', 'integer', 'min:1'],
            'items.*.variants' => ['required', 'array', 'min:1', 'max:500'],
            'items.*.variants.*' => ['required', 'array:id,color,size,stock,price'],
            'items.*.variants.*.id' => ['sometimes', 'nullable', 'integer', 'distinct'],
            'items.*.variants.*.color' => ['required', 'string', 'max:255'],
            'items.*.variants.*.size' => ['required', 'string', 'max:255'],
            'items.*.variants.*.stock' => ['required', 'integer', 'min:0'],
            'items.*.variants.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
        ];
    }
}
