using System.Security.Claims; using FastEndpoints; using TrackQrApi.Features.Plans.Services; namespace TrackQrApi.Features.Plans.Endpoints; public class GetUsageRequest { public Guid? WorkspaceId { get; set; } } public record UsageResponse( int Workspaces, int Links, int QRCodes, int Domains, int EventsThisMonth, string Plan, LimitsResponse Limits ); public record LimitsResponse( int MaxWorkspaces, int MaxLinks, int MaxQRCodes, int MaxDomains, int MaxEventsPerMonth, bool HasCustomDomains, bool HasPasswordProtection ); public class GetUsageEndpoint(IPlanLimitsService planLimits) : Endpoint { public override void Configure() { Get("/usage"); } public override async Task HandleAsync(GetUsageRequest req, CancellationToken ct) { var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); if (req.WorkspaceId.HasValue) { var wsUsage = await planLimits.GetWorkspaceUsageAsync(req.WorkspaceId.Value, ct); var response = new UsageResponse( 1, wsUsage.Links, wsUsage.QRCodes, wsUsage.Domains, wsUsage.EventsThisMonth, wsUsage.Plan.ToString(), new LimitsResponse( wsUsage.Limits.MaxWorkspaces, wsUsage.Limits.MaxLinksPerWorkspace, wsUsage.Limits.MaxQRCodesPerWorkspace, wsUsage.Limits.MaxDomainsPerWorkspace, wsUsage.Limits.MaxEventsPerMonth, wsUsage.Limits.HasCustomDomains, wsUsage.Limits.HasPasswordProtection ) ); await HttpContext.Response.SendAsync(response, cancellation: ct); } else { var usage = await planLimits.GetUsageAsync(userId, ct); var limits = planLimits.GetLimits(usage.HighestPlan); var response = new UsageResponse( usage.TotalWorkspaces, usage.TotalLinks, usage.TotalQRCodes, usage.TotalDomains, usage.EventsThisMonth, usage.HighestPlan.ToString(), new LimitsResponse( limits.MaxWorkspaces, limits.MaxLinksPerWorkspace, limits.MaxQRCodesPerWorkspace, limits.MaxDomainsPerWorkspace, limits.MaxEventsPerMonth, limits.HasCustomDomains, limits.HasPasswordProtection ) ); await HttpContext.Response.SendAsync(response, cancellation: ct); } } }