namespace Adapters.Driving.Api.Middleware;

using Domain.Exceptions;
using FluentValidation;

public class GraphQLErrorFilter : IErrorFilter
{
    public IError OnError(IError error)
    {
        return error.Exception switch
        {
            DomainException domainException => error
                .WithMessage(domainException.Message)
                .WithCode(domainException.Code),

            ValidationException validationException => error
                .WithMessage("Validation failed")
                .WithCode("VALIDATION_ERROR")
                .SetExtension("errors", validationException.Errors
                    .Select(e => new { e.PropertyName, e.ErrorMessage })),

            ArgumentException argException => error
                .WithMessage(argException.Message)
                .WithCode("INVALID_ARGUMENT"),

            _ => error.WithMessage(error.Exception?.Message ?? error.Message)
        };
    }
}
