<?php

namespace App\Domains\FiestaFutbolInfantil\Requests;

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

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

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

        return [
            'entries' => ['required', 'array', 'min:1', 'max:100'],
            'entries.*' => ['required', 'array:id,title,description,event_date_ids,stock,price'],
            'entries.*.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', 'Entradas'))
                ),
            ],
            'entries.*.title' => ['required', 'string', 'max:255'],
            'entries.*.description' => ['sometimes', 'nullable', 'string'],
            'entries.*.event_date_ids' => ['required', 'array', 'min:1'],
            'entries.*.event_date_ids.*' => [
                'required',
                'integer',
                Rule::exists('event_dates', 'id')->where(
                    fn ($query) => $query->where('tenant_code', $tenantCode)
                ),
            ],
            'entries.*.stock' => ['required', 'integer', 'min:0'],
            'entries.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
        ];
    }

    /** @return array<int, callable> */
    public function after(): array
    {
        return [
            function (Validator $validator): void {
                foreach ($this->input('entries', []) as $index => $entry) {
                    if (! is_array($entry)) {
                        continue;
                    }

                    $dateIds = $entry['event_date_ids'] ?? [];

                    if (! is_array($dateIds)) {
                        continue;
                    }

                    if (count($dateIds) !== count(array_unique($dateIds))) {
                        $validator->errors()->add(
                            "entries.{$index}.event_date_ids",
                            'Las fechas de una entrada no pueden repetirse.',
                        );
                    }
                }
            },
        ];
    }
}
