<?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\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class StoreCustomFieldRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('custom_fields.create') ?? false;
    }

    public function rules(): array
    {
        $tenantId = (int) $this->user()?->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')->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'],
        ];
    }

    protected function prepareForValidation(): void
    {
        $name = (string) $this->input('name', '');
        $slug = (string) $this->input('slug', '');
        if ($slug === '' && $name !== '') {
            $this->merge(['slug' => Str::slug($name)]);
        }
        $this->merge([
            'is_required' => $this->boolean('is_required'),
            'is_active' => $this->boolean('is_active', true),
        ]);
    }

    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'));
                }
            }
        });
    }
}
