<?php

namespace App\Modules\Customization\CustomFields\Services;

use App\Modules\Customization\CustomFields\Models\CustomField;
use App\Modules\Customization\CustomFields\Support\CustomFieldType;

final class CustomFieldRuleBuilder
{
    /**
     * @return array<string, list<string|object>>
     */
    public static function rulesForInput(CustomField $field): array
    {
        $key = 'custom_fields.'.$field->slug;
        $rules = [];
        if ($field->is_required) {
            $rules[] = 'required';
        } else {
            $rules[] = 'nullable';
        }

        $rules = array_merge($rules, self::typeRules($field->field_type));
        foreach (self::parseExtraRules((string) ($field->validation_rules ?? '')) as $r) {
            $rules[] = $r;
        }

        return [$key => $rules];
    }

    /**
     * @return list<string>
     */
    private static function typeRules(string $type): array
    {
        return match ($type) {
            CustomFieldType::TEXT => ['string', 'max:2000'],
            CustomFieldType::PHONE => ['string', 'max:40'],
            CustomFieldType::URL => ['string', 'max:2000', 'url'],
            CustomFieldType::TEXTAREA => ['string', 'max:10000'],
            CustomFieldType::NUMBER => ['numeric'],
            CustomFieldType::EMAIL => ['email', 'max:255'],
            CustomFieldType::SELECT, CustomFieldType::RADIO => ['string', 'max:500'],
            CustomFieldType::CHECKBOX => ['boolean'],
            CustomFieldType::DATE => ['date'],
            CustomFieldType::FILE => ['file', 'max:10240', 'mimes:pdf,doc,docx,jpg,jpeg,png'],
            default => ['string', 'max:2000'],
        };
    }

    /**
     * @return list<string>
     */
    private static function parseExtraRules(string $raw): array
    {
        $raw = trim($raw);
        if ($raw === '') {
            return [];
        }
        $allowed = [];
        foreach (explode('|', $raw) as $part) {
            $part = trim($part);
            if (preg_match('/^max:\d+$/', $part) === 1) {
                $allowed[] = $part;
            }
            if (preg_match('/^min:\d+$/', $part) === 1) {
                $allowed[] = $part;
            }
        }

        return $allowed;
    }
}
