<?php

namespace App\Http\Requests\Admin;

use App\Models\Language;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    public function rules(): array
    {
        $tagId = $this->route('tag')?->id;
        $defaultLocale = Language::where('site_default', true)
            ->where('status', true)
            ->value('a2_iso');

        $rules = [
            'slug'  => ['required', 'string', 'regex:/^[a-z0-9-]+$/',
                Rule::unique('tags', 'slug')->ignore($tagId)],
            'color' => ['nullable', 'regex:/^#[0-9a-fA-F]{6}$/'],
            'icon'  => ['nullable', 'string', 'max:64'],
            'translations' => ['array'],
            "translations.{$defaultLocale}.name" => ['required', 'string', 'max:128'],
        ];

        foreach (Language::where('status', true)->pluck('a2_iso') as $locale) {
            if ($locale !== $defaultLocale) {
                $rules["translations.{$locale}.name"] = ['nullable', 'string', 'max:128'];
            }
            $rules["translations.{$locale}.description"] = ['nullable', 'string', 'max:1024'];
        }

        return $rules;
    }
}
