package hander

import (
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/msg"
	"git.noahlan.cn/noahlan/ntool/nlog"
)

// HandleEntErr returns errors dealing with default functions.
func HandleEntErr(err error, detail any) error {
	logger := nlog.WithCallerSkip(1)
	if err != nil {
		switch {
		case ent.IsNotFound(err):
			// 未找到数据实体
			logger.Errorw(err.Error(), nlog.Field("detail", detail))
			return nstatus.NewBizErr(code.StatusNotFound, msg.ObjectNotFound)
		case ent.IsConstraintError(err):
			// 创建/更新时，发生约束错误
			logger.Errorw(err.Error(), nlog.Field("detail", detail))
			return nstatus.NewBizErr(code.StatusConflict, msg.ConstraintError)
		case ent.IsValidationError(err):
			// 数据类型错误，验证错误
			logger.Errorw(err.Error(), nlog.Field("detail", detail))
			return nstatus.NewBizErr(code.StatusBadRequest, msg.ValidationError)
		case ent.IsNotSingular(err):
			// 查询时发生，非单一实体错误，通常是因为记录中存在多个实体，查询单个实体时未添加Limit
			logger.Errorw(err.Error(), nlog.Field("detail", detail))
			return nstatus.NewBizErr(code.StatusBadRequest, msg.NotSingularError)
		default:
			logger.Errorw("database error", nlog.Field("err", err.Error()), nlog.Field("detail", detail))
			return nstatus.NewGrpcInternalErr(msg.DatabaseError)
		}
	}
	return err
}
