using AutoMapper;
using Microsoft.AspNetCore.Mvc.Formatters.Xml;
using ConvertToDTE;
using ConvertToDTE.Model;
using System.Xml.Serialization;
using System.IO;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAutoMapper(typeof(Program));

// Agrega soporte para XML
builder.Services.AddControllers()
    .AddXmlSerializerFormatters();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapPost("/Dte", (SourceClass request, IMapper mapper) =>
{
    // Mapea el SourceClass a la entidad DTE
    var dte = mapper.Map<DTE>(request);

    // Serializa el objeto DTE a XML sdas
    var xmlContent = SerializeToXml(dte);

    // Retorna el XML como respuesta
    return Results.Text(xmlContent, "application/xml");
})
.WithName("Post DTE")
.WithOpenApi();

app.Run();

static string SerializeToXml(DTE dto)
{
    XmlSerializer serializer = new XmlSerializer(typeof(DTE));
    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
    namespaces.Add("", ""); // Eliminar los prefijos de los namespaces
    using (StringWriter writer = new StringWriter())
    {
        serializer.Serialize(writer, dto, namespaces);
        return writer.ToString();
    }
}