<?php

namespace App\Domains\Event\Requests;

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

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

    /** @return array<string, mixed> */
    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:255'],
            'location' => ['required', 'string', 'max:255'],
            'dates' => ['required', 'array', 'min:1'],
            'dates.*' => ['required', 'array:date,start_time,end_time'],
            'dates.*.date' => ['required', 'date_format:Y-m-d', 'distinct'],
            'dates.*.start_time' => ['required', 'date_format:H:i'],
            'dates.*.end_time' => ['required', 'date_format:H:i'],
            'social_media' => ['sometimes', 'array'],
            'social_media.*' => ['required', 'array:code,url,orden'],
            'social_media.*.code' => [
                'required',
                'string',
                'distinct',
                Rule::exists('social_media', 'code'),
            ],
            'social_media.*.url' => ['required', 'url', 'max:2048'],
            'social_media.*.orden' => ['sometimes', 'integer', 'min:0', 'distinct'],
            'contact' => ['sometimes', 'array:whatsapp_url,instagram_url,facebook_url'],
            'contact.whatsapp_url' => ['nullable', 'url', 'max:2048'],
            'contact.instagram_url' => ['nullable', 'url', 'max:2048'],
            'contact.facebook_url' => ['nullable', 'url', 'max:2048'],
        ];
    }

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

                if (! array_key_exists('social_media', $input) && ! array_key_exists('contact', $input)) {
                    $validator->errors()->add(
                        'social_media',
                        'The social media field is required.'
                    );
                }
            },
        ];
    }
}
