package usecase

import (
	"errors"
	"strings"

	errs "gateway/internal/library/errors"
	"gateway/internal/library/errors/code"
	permission "gateway/internal/model/permission/domain"
)

var errb = errs.For(code.Permission)

// wrapRepoErr converts repository sentinel errors into structured errs
// with the right HTTP/gRPC mapping. All usecase methods funnel repo
// errors through this helper to keep the surface uniform.
func wrapRepoErr(err error, msg ...string) error {
	if err == nil {
		return nil
	}
	switch {
	case errors.Is(err, permission.ErrPermissionNotFound):
		return errb.ResNotFound("permission not found").WithCause(err)
	case errors.Is(err, permission.ErrPermissionDup):
		return errb.ResAlreadyExist("permission already exists").WithCause(err)
	case errors.Is(err, permission.ErrRoleNotFound):
		return errb.ResNotFound("role not found").WithCause(err)
	case errors.Is(err, permission.ErrRoleDuplicate):
		return errb.ResAlreadyExist("role already exists in tenant").WithCause(err)
	case errors.Is(err, permission.ErrRoleSystemImmutable):
		return errb.ResInvalidState("system role is immutable").WithCause(err)
	case errors.Is(err, permission.ErrRoleNotInTenant):
		return errb.ResNotFound("role not in tenant").WithCause(err)
	case errors.Is(err, permission.ErrRoleKeyReserved):
		return errb.InputInvalidFormat("role key uses reserved prefix").WithCause(err)
	case errors.Is(err, permission.ErrRoleKeyInvalid):
		return errb.InputInvalidFormat("role key format invalid").WithCause(err)
	case errors.Is(err, permission.ErrUserRoleNotFound):
		return errb.ResNotFound("user role not found").WithCause(err)
	case errors.Is(err, permission.ErrUserRoleDuplicate):
		return errb.ResAlreadyExist("user role already assigned").WithCause(err)
	case errors.Is(err, permission.ErrRoleMappingNotFound):
		return errb.ResNotFound("role mapping not found").WithCause(err)
	case errors.Is(err, permission.ErrRoleMappingDuplicate):
		return errb.ResAlreadyExist("role mapping already exists").WithCause(err)
	case errors.Is(err, permission.ErrCasbinNotConfigured):
		return errb.SysNotImplemented("casbin enforcer not configured").WithCause(err)
	case errors.Is(err, permission.ErrInvalidStatus):
		return errb.InputInvalidFormat("invalid status").WithCause(err)
	}
	if e := errs.FromError(err); e != nil {
		return err
	}
	m := strings.TrimSpace(strings.Join(msg, " "))
	if m == "" {
		m = "permission repository error"
	}
	return errb.DBError(m).WithCause(err)
}
