<?php

namespace App\Modules\Customization\CustomFields\Requests;

use App\Modules\Customization\CustomFields\Models\CustomField;
use App\Modules\Customization\CustomFields\Support\CustomFieldType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class UpdateCustomFieldRequest extends FormRequest
{
    public function authorize(): bool
    {
        $field = $this->route('custom_field');

        return $field instanceof CustomField
            && ($this->user()?->can('custom_fields.update', $field) ?? false);
    }

    public function rules(): array
    {
        /** @var CustomField $field */
        $field = $this->route('custom_field');
        $tenantId = (int) $field->tenant_id;

        return [
            'module' => ['required', 'string', 'max:50', Rule::in(['hr'])],
            'entity' => ['required', 'string', 'max:80', Rule::in(['employees'])],
            'name' => ['required', 'string', 'max:255'],
            'slug' => [
                'required', 'string', 'max:120', 'alpha_dash',
                Rule::unique('custom_fields', 'slug')
                    ->ignore($field->id)
                    ->where(fn ($q) => $q
                        ->where('tenant_id', $tenantId)
                        ->where('module', $this->input('module'))
                        ->where('entity', $this->input('entity'))),
            ],
            'field_type' => ['required', 'string', Rule::in(CustomFieldType::all())],
            'is_required' => ['sometimes', 'boolean'],
            'is_active' => ['sometimes', 'boolean'],
            'validation_rules' => ['nullable', 'string', 'max:2000'],
            'placeholder' => ['nullable', 'string', 'max:255'],
            'help_text' => ['nullable', 'string', 'max:2000'],
            'options' => ['nullable', 'array'],
            'options.*.label' => ['nullable', 'string', 'max:255'],
            'options.*.value' => ['nullable', 'string', 'max:255'],
            'sort_order' => ['sometimes', 'integer', 'min:0', 'max:999999'],
        ];
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'is_required' => $this->boolean('is_required'),
            'is_active' => $this->boolean('is_active', true),
        ]);
        if ($this->filled('sort_order')) {
            $this->merge(['sort_order' => (int) $this->input('sort_order')]);
        }
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            if ($validator->errors()->isNotEmpty()) {
                return;
            }
            $type = (string) $this->input('field_type');
            $opts = $this->input('options', []);
            if (in_array($type, [CustomFieldType::SELECT, CustomFieldType::RADIO], true)) {
                if (! is_array($opts) || count(array_filter($opts, fn ($r) => is_array($r) && (($r['label'] ?? '') !== '' || ($r['value'] ?? '') !== ''))) < 1) {
                    $validator->errors()->add('options', __('custom_fields.validation.options_required'));
                }
            }
        });
    }
}
