using SharedKernel.Results;

namespace Web.Api.Common;

public static class CustomResults
{
    public static IResult Problem(Result result)
    {
        if (result.IsSuccess)
        {
            throw new InvalidOperationException();
        }

        var statusCode = GetStatusCode(result.Error.Type);

        if (result.Error is ValidationError validationError)
        {
            return ApiResponse.Fail(
                statusCode,
                result.Error.Description,
                validationError.Errors.Select(e => new
                {
                    code = e.Code,
                    description = e.Description
                })
            );
        }

        return ApiResponse.Fail(statusCode, result.Error.Description);
    }

    private static int GetStatusCode(ErrorType errorType) => errorType switch
    {
        ErrorType.Validation or ErrorType.Problem => StatusCodes.Status400BadRequest,
        ErrorType.Unauthorized => StatusCodes.Status401Unauthorized,
        ErrorType.NotFound => StatusCodes.Status404NotFound,
        ErrorType.Forbidden => StatusCodes.Status403Forbidden,
        ErrorType.Conflict => StatusCodes.Status409Conflict,
        ErrorType.MethodNotAllowed => StatusCodes.Status405MethodNotAllowed,
        _ => StatusCodes.Status500InternalServerError
    };
}