package usecase

import (
	"errors"
	"strings"

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

var errb = errs.For(code.Member)

func wrapRepoErr(err error, msg ...string) error {
	if err == nil {
		return nil
	}
	if errors.Is(err, member.ErrNotFound) {
		return errb.ResNotFound("member", "").WithCause(err)
	}
	if errors.Is(err, member.ErrTenantNotFound) {
		return errb.ResNotFound("tenant", "").WithCause(err)
	}
	if errors.Is(err, member.ErrChallengeNotFound) {
		return errb.ResNotFound("otp challenge", "").WithCause(err)
	}
	if errors.Is(err, member.ErrTOTPEnrollMissing) {
		return errb.ResNotFound("totp enroll", "").WithCause(err)
	}
	if errors.Is(err, member.ErrDuplicateMember) {
		return errb.ResAlreadyExist("member already exists").WithCause(err)
	}
	if errors.Is(err, member.ErrDuplicateTenant) {
		return errb.ResAlreadyExist("tenant already exists").WithCause(err)
	}
	if e := errs.FromError(err); e != nil {
		return err
	}
	m := strings.TrimSpace(strings.Join(msg, " "))
	if m == "" {
		m = "member repository error"
	}
	return errb.DBError(m).WithCause(err)
}
