using Knot.Modules.TelegramImport.Application.TelegramImport;
using Knot.Modules.TelegramImport.Application.TelegramImport.DTOs;
using Knot.Modules.TelegramImport.Infrastructure.Background;
using Knot.Shared.Kernel;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;

namespace Knot.Modules.TelegramImport.Presentation.Endpoints;

public static class TelegramImportEndpoints
{
    public static void MapTelegramImportEndpoints(this WebApplication app)
    {
        var group = app.MapGroup("api/import/telegram").RequireAuthorization();

        group.MapPost("analyze", async (HttpRequest req, ISender sender, CancellationToken ct) =>
        {
            if (!req.HasFormContentType) return Results.BadRequest("No file uploaded.");
            var form = await req.ReadFormAsync(ct);
            var file = form.Files.FirstOrDefault();
            if (file == null) return Results.BadRequest("No file uploaded.");

            using var stream = file.OpenReadStream();
            var result = await sender.Send(new AnalyzeImportCommand(stream, file.FileName), ct);
            return result.IsSuccess ? Results.Ok(result.Value) : Results.BadRequest(result.Error.Description ?? result.Error.Code);
        }).DisableAntiforgery().WithMetadata(new Microsoft.AspNetCore.Mvc.RequestSizeLimitAttribute(1000000000));

        group.MapPost("execute", async ([FromBody] ExecuteImportRequest req, ISender sender, IUserContext userContext, CancellationToken ct) =>
        {
            var command = new ExecuteImportCommand(userContext.UserId, req.Token, req.GroupName, req.Mapping, req.TotalMessages);
            var result = await sender.Send(command, ct);
            return result.IsSuccess ? Results.Ok(result.Value) : Results.BadRequest(result.Error.Description ?? result.Error.Code);
        });

        group.MapGet("status/{jobId:guid}", (Guid jobId, IImportJobStore jobStore) =>
        {
            if (jobStore.TryGet(jobId, out var info))
            {
                return Results.Ok(info);
            }
            return Results.NotFound();
        });
    }
}


