<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class ProductCustomFieldSaveRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        $product = $this->route('product');

        return $this->user()->can('update', $product);
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'type' => 'required|in:text,textarea,dropdown,checkbox',
            'validation_rules' => 'nullable|array',
            'dropdown_options' => 'nullable|array',
            // PRC-786 — tip-duyarlı default_value: checkbox→0/1, dropdown→seçenek value'su.
            'default_value' => ['nullable', 'string', 'max:500', function ($attr, $value, $fail) {
                if (! \App\Models\ProductCustomField::isValidDefaultValue($this->input('type'), $this->input('dropdown_options'), $value)) {
                    $fail(__('admin/products.custom_fields_default_value_invalid'));
                }
            }],
            'admin_only' => 'boolean',
            'visible_on_client' => 'boolean',
            'required_from_client' => 'boolean',
            'visible_on_invoice' => 'boolean',
            'client_locked' => 'boolean',
            'order' => 'integer|min:0',
            'title' => 'nullable|string',
            'description' => 'nullable|string',
            'ai_translate' => 'boolean',
            'manual_translations' => 'nullable|array',
            'manual_translations.*.label' => 'nullable|string|max:255',
            'manual_translations.*.description' => 'nullable|string',
            'translations' => 'nullable|array',
            'translations.*.label' => 'nullable|string|max:255',
            'translations.*.description' => 'nullable|string',
            'translations.*.placeholder' => 'nullable|string',
        ];
    }

    /**
     * Get custom error messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'type.required' => __('admin/products.custom_fields.validation.type.required'),
            'type.in' => __('admin/products.custom_fields.validation.type.in'),
            'order.integer' => __('admin/products.custom_fields.validation.order.integer'),
            'order.min' => __('admin/products.custom_fields.validation.order.min'),
            'manual_translations.*.label.max' => __('admin/products.custom_fields.validation.label.max'),
            'translations.*.label.max' => __('admin/products.custom_fields.validation.label.max'),
        ];
    }
}
