using ApiOPE.Configuration;
using ApiOPE.Contracts;
using Microsoft.Extensions.Options;

namespace ApiOPE.Services;

public sealed class OpeFieldMapper
{
    public static readonly IReadOnlySet<string> SupportedInternalFields = new HashSet<string>(
    [
        "fechaDenuncia",
        "numeroDenunciaCanal",
        "aQuienDenuncia",
        "resumenDenuncia",
        "fechaHechos",
        "lugarHechos",
        "ambitoCompetencias",
        "solicitaProteccion",
        "sexoDenunciante",
        "autorizaRemisionDenuncia",
        "autorizaNotificacionesViaSms",
        "preferenciaNotificacionSeguimientoDenuncia"
    ],
        StringComparer.Ordinal);

    private readonly string[] _outputFields;

    public OpeFieldMapper(IOptions<OpeOptions> options)
    {
        _outputFields = options.Value.OutputFields.ToArray();
    }

    public OpeDataEnvelope Map(InternalGestionaFieldsResponse source)
    {
        var output = new Dictionary<string, OpeFieldValue>(StringComparer.Ordinal);

        for (var index = 0; index < _outputFields.Length; index++)
        {
            var internalField = _outputFields[index];
            if (!source.Data.TryGetValue(internalField, out var value))
            {
                throw new InvalidDataException(
                    $"La API interna no ha devuelto el campo configurado '{internalField}'.");
            }

            output[$"FIELD_{index}"] = new OpeFieldValue("STRING", value.Value?.Trim() ?? string.Empty);
        }

        return new OpeDataEnvelope(output);
    }
}
