using Health.Application.Calendars;

namespace Health.WebApi.Endpoints;

public static class CalendarEndpoints
{
    public static void MapCalendarEndpoints(this WebApplication app)
    {
        var group = app.MapGroup("/api/calendar").RequireAuthorization();

        group.MapGet("/", async (int year, int month, HttpContext http, ICalendarService calendar, CancellationToken ct) =>
        {
            if (year is < 2000 or > 2100 || month is < 1 or > 12)
                return Results.Ok(new { code = 400, data = (object?)null, message = "年月格式错误" });

            var result = await calendar.GetMonthAsync(GetUserId(http), year, month, ct);
            return Results.Ok(new { code = 0, data = result, message = (string?)null });
        });

        group.MapGet("/day", async (string date, HttpContext http, ICalendarService calendar, CancellationToken ct) =>
        {
            if (!DateOnly.TryParse(date, out var parsedDate))
                return Results.Ok(new { code = 400, data = (object?)null, message = "日期格式错误" });

            var result = await calendar.GetDayAsync(GetUserId(http), parsedDate, ct);
            return Results.Ok(new { code = 0, data = result, message = (string?)null });
        });
    }

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