package billing

import (
	"errors"
	"net/http"

	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/store/storeerr"
)

func mapBillingDependencyError(err error) error {
	if errors.Is(err, storeerr.ErrNotFound) {
		return api.NewHTTPErrorWithCodeAndCause(http.StatusNotFound, "Billing resource not found", billingErrorNotFound, err)
	}
	if errors.Is(err, storeerr.ErrForbidden) {
		return api.NewHTTPErrorWithCodeAndCause(http.StatusForbidden, "Billing request is forbidden", billingErrorForbidden, err)
	}
	if errors.Is(err, storeerr.ErrConflict) {
		return api.NewHTTPErrorWithCodeAndCause(http.StatusConflict, "Billing request conflicts with current state", billingErrorConflict, err)
	}
	if errors.Is(err, storeerr.ErrBadRequest) {
		return api.NewHTTPErrorWithCodeAndCause(http.StatusBadRequest, "Billing request is invalid", billingErrorInvalidInput, err)
	}
	if errors.Is(err, storeerr.ErrUnprocessable) {
		return api.NewHTTPErrorWithCodeAndCause(http.StatusUnprocessableEntity, "Billing request is invalid", billingErrorInvalidInput, err)
	}
	var maasErr MaaSClientError
	if errors.As(err, &maasErr) {
		switch maasErr.StatusCode {
		case http.StatusNotFound:
			return api.NewHTTPErrorWithCodeAndCause(http.StatusNotFound, "Billing resource not found", billingErrorNotFound, err)
		case http.StatusConflict:
			return api.NewHTTPErrorWithCodeAndCause(http.StatusConflict, "Billing request conflicts with current state", billingErrorConflict, err)
		case http.StatusBadRequest, http.StatusUnprocessableEntity:
			return api.NewHTTPErrorWithCodeAndCause(http.StatusUnprocessableEntity, "Billing request is invalid", billingErrorInvalidInput, err)
		default:
			return dependencyUnavailable(err)
		}
	}
	return dependencyUnavailable(err)
}

func dependencyUnavailable(cause error) error {
	message := "Billing dependency is unavailable"
	return api.NewHTTPErrorWithCodeAndCause(http.StatusServiceUnavailable, message, billingErrorUnavailable, cause)
}
