using System.Security.Claims;
using Health.Application.Notifications;

namespace Health.WebApi.Endpoints;

public static class NotificationEndpoints
{
    public static void MapNotificationEndpoints(this WebApplication app)
    {
        var group = app.MapGroup("/api/notifications").RequireAuthorization();

        group.MapGet("/pending", async (HttpContext http, IInAppNotificationService notifications, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            if (userId == Guid.Empty) return Results.Unauthorized();
            var result = await notifications.GetPendingAsync(userId, ct);
            return Results.Ok(new { code = 0, data = result, message = (string?)null });
        });

        group.MapGet("", async (HttpContext http, IInAppNotificationService notifications, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            if (userId == Guid.Empty) return Results.Unauthorized();
            var result = await notifications.GetHistoryAsync(userId, ct);
            return Results.Ok(new
            {
                code = 0,
                data = new { unreadCount = result.Count(x => !x.IsRead), items = result },
                message = (string?)null
            });
        });

        group.MapPost("/{id:guid}/acknowledge", async (Guid id, HttpContext http, IInAppNotificationService notifications, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            if (userId == Guid.Empty) return Results.Unauthorized();
            var acknowledged = await notifications.AcknowledgeAsync(userId, id, ct);
            return Results.Ok(new { code = 0, data = new { acknowledged }, message = (string?)null });
        });

        group.MapPost("/read-all", async (HttpContext http, IInAppNotificationService notifications, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            if (userId == Guid.Empty) return Results.Unauthorized();
            var count = await notifications.MarkAllReadAsync(userId, ct);
            return Results.Ok(new { code = 0, data = new { count }, message = (string?)null });
        });


        group.MapDelete("/{id:guid}", async (Guid id, HttpContext http, IInAppNotificationService notifications, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            if (userId == Guid.Empty) return Results.Unauthorized();
            var deleted = await notifications.DeleteAsync(userId, id, ct);
            return deleted
                ? Results.Ok(new { code = 0, data = new { deleted = true }, message = (string?)null })
                : Results.NotFound(new { code = 404, data = (object?)null, message = "通知不存在" });
        });
    }

    private static Guid GetUserId(HttpContext http) =>
        Guid.TryParse(http.User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
}
