using Microsoft.AspNetCore.Diagnostics;

namespace Web.Api.Common;

internal sealed class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken
    ) {
        if (exception is BadHttpRequestException)
        {
            logger.LogWarning(exception, "Bad request");

            httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            httpContext.Response.ContentType = "application/json";

            await httpContext.Response.WriteAsJsonAsync(new ApiResponse
            {
                Success = false,
                Status = StatusCodes.Status400BadRequest,
                Message = "Invalid request body"
            }, cancellationToken);

            return true;
        }

        logger.LogError(exception, "Unhandled exception occurred");

        httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
        httpContext.Response.ContentType = "application/json";

        await httpContext.Response.WriteAsJsonAsync(new ApiResponse
        {
            Success = false,
            Status = StatusCodes.Status500InternalServerError,
            Message = "Server failure"
        }, cancellationToken);

        return true;
    }
}