using FastEndpoints;
using TaxBaik.Application.Services;

namespace TaxBaik.Web.Endpoints.AdminDashboard;

public class GetMonthlyStatsEndpoint : Endpoint<MonthlyStatsQuery, MonthlyStatsResponse>
{
    private readonly AdminDashboardService _dashboardService;

    public GetMonthlyStatsEndpoint(AdminDashboardService dashboardService)
    {
        _dashboardService = dashboardService;
    }

    public override void Configure()
    {
        Get("/api/admin-dashboard/monthly-stats");
        Policies("AdminOnly");
    }

    public override async Task HandleAsync(MonthlyStatsQuery request, CancellationToken ct)
    {
        try
        {
            var stats = await _dashboardService.GetMonthlyStatsAsync(request.Month, ct);

            // Convert dynamic result to typed response
            var statsDict = (dynamic)stats;
            await SendAsync(new MonthlyStatsResponse
            {
                Month = statsDict.month,
                TotalInquiries = statsDict.totalInquiries,
                ConsultingCount = statsDict.consultingCount,
                CompletedCount = statsDict.completedCount,
                NewCount = statsDict.newCount,
                CompletionRate = statsDict.completionRate
            }, 200, cancellation: ct);
        }
        catch (Exception)
        {
            await SendErrorsAsync(500, ct);
        }
    }
}
