<?php

namespace App\Http\Requests\Admin;

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

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

    public function rules(): array
    {
        return [
            'name' => ['required','string','max:80'],
            'slug' => ['required','string','max:80','regex:/^[a-z0-9-]+$/', 'unique:content_types,slug'],
            'is_single' => ['required','boolean'],

            'locales' => ['required','array','min:1'],
            'locales.*' => ['required','string','max:10'],
            'default_locale' => ['required','string','max:10'],
            'schema' => ['required','array'],
            'schema.fields' => ['required','array'],
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($v) {
            $locales = $this->input('locales', []);
            $default = $this->input('default_locale');

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