<?php

namespace App\Domains\FiestaFutbolInfantil\Requests;

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

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

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

        return [
            'variants' => ['required', 'array', 'min:1', 'max:500'],
            'variants.*' => ['required', 'array:id,event_date_id,schedule,service,description,stock,price'],
            'variants.*.id' => ['sometimes', 'nullable', 'integer', 'distinct'],
            'variants.*.event_date_id' => [
                'required',
                'integer',
                Rule::exists('event_dates', 'id')->where(
                    fn ($query) => $query->where('tenant_code', $tenantCode)
                ),
            ],
            'variants.*.schedule' => ['required', 'string', 'max:255'],
            'variants.*.service' => ['required', 'string', 'max:255'],
            'variants.*.description' => ['sometimes', 'nullable', 'string'],
            'variants.*.stock' => ['required', 'integer', 'min:0'],
            'variants.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
        ];
    }

    /** @return array<int, callable> */
    public function after(): array
    {
        return [
            function (Validator $validator): void {
                $seen = [];

                foreach ($this->input('variants', []) as $index => $variant) {
                    if (! is_array($variant)) {
                        continue;
                    }

                    $key = implode('|', [
                        $variant['event_date_id'] ?? '',
                        mb_strtolower(trim((string) ($variant['schedule'] ?? ''))),
                        mb_strtolower(trim((string) ($variant['service'] ?? ''))),
                    ]);

                    if (isset($seen[$key])) {
                        $validator->errors()->add(
                            "variants.{$index}",
                            'La combinación de fecha, horario y servicio no puede repetirse.',
                        );
                    }

                    $seen[$key] = true;
                }
            },
        ];
    }
}
