using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

namespace JobTrackerApi.Services;

public sealed class AiUsageLimitExceptionHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
    {
        if (exception is not AiUsageLimitException limit) return false;

        httpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
        await httpContext.Response.WriteAsJsonAsync(new ProblemDetails
        {
            Status = StatusCodes.Status429TooManyRequests,
            Title = "AI usage limit reached",
            Detail = limit.Message,
            Extensions =
            {
                ["code"] = limit.Code,
                ["traceId"] = httpContext.TraceIdentifier,
            },
        }, cancellationToken);
        return true;
    }
}
