using Tiku.Api.Middleware;
using Tiku.Api.Controllers;
using Tiku.Application.Learning;

namespace Tiku.Api.Modules.Student.Learning.Errors;

internal sealed class LearningExceptionProblemDetailsMapper : ExceptionProblemDetailsMapper
{
    public override IReadOnlyCollection<Type> HandledExceptionTypes { get; } =
    [typeof(LearningValidationException), typeof(LearningResourceNotFoundException), typeof(LearningAccessDeniedException)];

    public override bool TryMap(Exception exception, out ExceptionProblemDetailsMapping mapping)
    {
        return exception switch
        {
            LearningValidationException validation => Mapped(validation, ValidationStatus(validation.Code),
                validation.Code, out mapping),
            LearningResourceNotFoundException notFound => Mapped(notFound, StatusCodes.Status404NotFound,
                notFound.Code, out mapping),
            LearningAccessDeniedException => Mapped(exception, StatusCodes.Status403Forbidden,
                "learning_access_denied", out mapping),
            _ => NotMapped(out mapping)
        };
    }

    private static int ValidationStatus(string code) => code switch
    {
        "no_practice_questions" or "practice_session_empty" or "idempotency_conflict" or
            "practice_session_version_conflict" or "practice_client_sequence_conflict" or
            "practice_answer_conflict" or "practice_submission_conflict" or "practice_session_not_active" or
            "practice_session_expired" => StatusCodes.Status409Conflict,
        _ => StatusCodes.Status400BadRequest
    };
}
