package listing

import (
	"errors"
	"net/http"
	"strconv"

	"hfb_sys/backend/pkg/response"

	"github.com/gin-gonic/gin"
)

func writeListingError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrDependencyUnavailable):
		response.ServiceUnavailable(c, "数据库未连接")
	case errors.Is(err, ErrMissingTitle):
		response.BadRequest(c, "发布标题不能为空")
	case errors.Is(err, ErrMissingServerRegion):
		response.BadRequest(c, "请选择区服")
	case errors.Is(err, ErrInvalidPrice):
		response.BadRequest(c, "发布价格不正确")
	case errors.Is(err, ErrInvalidDeposit):
		response.BadRequest(c, "押金不能小于 0")
	case errors.Is(err, ErrDepositTooLow):
		response.BadRequest(c, "押金必须大于额外消耗品总价值")
	case errors.Is(err, ErrInvalidHafCoin):
		response.BadRequest(c, "哈夫币数量不正确")
	case errors.Is(err, ErrMissingScreenshot):
		response.BadRequest(c, "请至少上传一张账号截图")
	case errors.Is(err, ErrMissingOnlineTime):
		response.BadRequest(c, "请选择在线时间")
	case errors.Is(err, ErrInvalidOnlineTime):
		response.BadRequest(c, "在线时间不正确")
	case errors.Is(err, ErrAgreementRequired):
		response.BadRequest(c, "请先阅读并同意发布协议")
	case errors.Is(err, ErrMissingUploaderName):
		response.BadRequest(c, "上传人名称不能为空")
	case errors.Is(err, ErrMissingUploadData):
		response.BadRequest(c, "上传账号数据不能为空")
	case errors.Is(err, ErrUploaderNotFound):
		response.BadRequest(c, "未匹配到可用后台用户")
	case errors.Is(err, ErrUploaderAmbiguous):
		response.BadRequest(c, "上传人名称匹配到多个后台用户，请使用唯一用户名")
	case errors.Is(err, ErrTooManyUploadItems):
		response.BadRequest(c, "单次上传账号数量过多")
	case isUploadValidationError(err):
		response.BadRequest(c, err.Error())
	case isFireLevelTooLow(err):
		var levelErr FireLevelTooLowError
		errors.As(err, &levelErr)
		response.BadRequest(c, "烽火等级低于"+strconv.Itoa(levelErr.Min)+"级的号无法发布")
	case errors.Is(err, ErrInvalidInput):
		response.BadRequest(c, "发布信息不符合规则")
	case errors.Is(err, ErrListingLocked):
		response.Error(c, http.StatusConflict, "listing_locked", "当前发布不可修改")
	case IsNotFound(err):
		response.Error(c, http.StatusNotFound, "not_found", "发布不存在")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "发布服务暂时不可用")
	}
}

func isFireLevelTooLow(err error) bool {
	var levelErr FireLevelTooLowError
	return errors.As(err, &levelErr)
}

func isUploadValidationError(err error) bool {
	var validationErr UploadValidationError
	return errors.As(err, &validationErr)
}
