using Alchegos.HCI.Components;
using Alchegos.HCI.Filters;
using Alchegos.HCI.Models;
using Alchegos.HCI.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();
builder.Services.AddHttpClient();
builder.Services.AddSingleton<IChatSessionService, InMemoryChatSessionService>();
builder.Services.AddSingleton<IAuthenticationService, AuthenticationService>();
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "n8n", policy =>
    {
        policy.WithOrigins("http://n8n:5678");
    });
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();


app.UseAntiforgery();

app.MapStaticAssets();

app.MapPost("/api/chatwebhook", async (
    [FromBody] WebhookPayload payload,
    IChatSessionService chatSessionService,
    ILogger<Program> logger) =>
{
    if (string.IsNullOrEmpty(payload.SessionId))
    {
        logger.LogWarning("Received webhook payload without sessionId.");
        var errors = new Dictionary<string, string[]> {
            { nameof(payload.SessionId), ["sessionId is required."] }
        };
        return Results.ValidationProblem(errors,
            title: "One or more validation errors occurred.",
            statusCode: StatusCodes.Status400BadRequest);
    }

    if (payload.Action == "close_session")
    {
        logger.LogInformation("Webhook request received to close session: {SessionId}", payload.SessionId);
        await chatSessionService.TriggerSessionClosed(payload.SessionId);
        return Results.Ok(new { message = $"Session close requested for {payload.SessionId}" });
    }
    else if (!string.IsNullOrEmpty(payload.Output))
    {
        logger.LogInformation("Webhook request received with output for session: {SessionId}", payload.SessionId);
        await chatSessionService.TriggerMessageReceived(payload.SessionId, payload.Output);
        return Results.Ok(new { message = $"Output received for {payload.SessionId}" });
    }
    else
    {
        logger.LogWarning("Received webhook payload for session {SessionId} with neither 'output' nor 'action':'close_session'.", payload.SessionId);
        return Results.Problem(
            title: "Invalid payload content.",
            detail: "Payload must contain either a non-empty 'output' field or an 'action' field set to 'close_session'.",
            statusCode: StatusCodes.Status400BadRequest);
    }
})
    .WithTags("Chat Webhook")
    .AddEndpointFilter<WebhookAuthFilter>(); 

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.Run();