package usecase

import (
	"errors"
	"strings"

	errs "gateway/internal/library/errors"
	"gateway/internal/library/errors/code"
	authdomain "gateway/internal/model/auth/domain"
)

var errb = errs.For(code.Auth)

func wrapRepoErr(err error, msg ...string) error {
	if err == nil {
		return nil
	}
	if errors.Is(err, authdomain.ErrInviteNotFound) {
		return errb.ResNotFound("invite", "").WithCause(err)
	}
	if errors.Is(err, authdomain.ErrInviteExpired) {
		return errb.InputInvalidFormat("invite code expired").WithCause(err)
	}
	if errors.Is(err, authdomain.ErrInviteExhausted) {
		return errb.ResInsufficientQuota("invite code exhausted").WithCause(err)
	}
	if errors.Is(err, authdomain.ErrInviteLocked) {
		return errb.ResLocked("invite consume in progress").WithCause(err)
	}
	if errors.Is(err, authdomain.ErrDuplicateRegistrationMeta) {
		return errb.ResAlreadyExist("registration metadata already exists").WithCause(err)
	}
	if errors.Is(err, authdomain.ErrRegistrationSessionNotFound) {
		return errb.ResNotFound("registration session", "").WithCause(err)
	}
	if errors.Is(err, authdomain.ErrLoginSessionNotFound) {
		return errb.ResNotFound("login session", "").WithCause(err)
	}
	if e := errs.FromError(err); e != nil {
		return err
	}
	m := strings.TrimSpace(strings.Join(msg, " "))
	if m == "" {
		m = "auth repository error"
	}
	return errb.DBError(m).WithCause(err)
}
