<?php

namespace App\LeadExports;

/**
 * Value types a mapped lead-export field can declare. Used to validate a template /
 * export field_map and to type the properties in the generated OpenAPI document.
 */
class LeadExportFieldType
{
    public const STRING = 'string';
    public const INTEGER = 'integer';
    public const FLOAT = 'float';
    public const BOOLEAN = 'boolean';
    public const DATE = 'date';
    public const ARRAY = 'array';

    /** @var array<int, string> */
    public const TYPES = [
        self::STRING,
        self::INTEGER,
        self::FLOAT,
        self::BOOLEAN,
        self::DATE,
        self::ARRAY,
    ];

    /**
     * Coerce a resolved answer value into the configured type for the outbound payload.
     */
    public static function coerce(mixed $value, string $type): mixed
    {
        if ($value === null) {
            return null;
        }

        return match ($type) {
            self::INTEGER => is_numeric($value) ? (int) $value : $value,
            self::FLOAT => is_numeric($value) ? (float) $value : $value,
            self::BOOLEAN => filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? $value,
            self::ARRAY => is_array($value) ? $value : array_filter(array_map('trim', explode(',', (string) $value))),
            default => $value,
        };
    }
}
