<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        $id = $this->route('contentType')?->id ?? null;

        return [
            'name' => ['sometimes','string','max:80'],
            'slug' => ['sometimes','string','max:80','regex:/^[a-z0-9-]+$/', "unique:content_types,slug,{$id}"],
            'is_single' => ['sometimes','boolean'],

            'locales' => ['sometimes','array','min:1'],
            'locales.*' => ['required_with:locales','string','max:10'],
            'default_locale' => ['sometimes','string','max:10'],

            'schema' => ['sometimes','array'],
            'schema.fields' => ['sometimes','array'],
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($v) {
            if ($this->has('locales') || $this->has('default_locale')) {
                $locales = $this->input('locales', $this->route('contentType')?->locales ?? []);
                $default = $this->input('default_locale', $this->route('contentType')?->default_locale);

                if ($default && is_array($locales) && !in_array($default, $locales, true)) {
                    $v->errors()->add('default_locale', 'default_locale must exist inside locales.');
                }
            }
        });
    }
}
