package usecase

import (
	errs "backend/pkg/library/errors"
	"context"
	"math"

	"backend/pkg/member/domain/entity"

	GIDLib "code.30cm.net/digimon/library-go/utils/invited_code"
)

func (use *MemberUseCase) Generate(ctx context.Context) (string, error) {
	var data entity.AutoID
	err := use.GenerateUID.Inc(ctx, &data)
	if err != nil {
		e := errs.DBErrorErrorL(
			use.Logger,
			[]errs.LogField{
				{Key: "func", Val: "AutoIDModel.Inc"},
				{Key: "err", Val: err.Error()},
			},
			"failed to inc account num")

		return "", e
	}

	// 使用 uint64 處理，避免溢出
	sum := GIDLib.InitAutoID + data.Counter
	if sum > math.MaxInt64 {
		return "",
			errs.InputInvalidRangeErrorL(
				use.Logger,
				[]errs.LogField{
					{Key: "func", Val: "MemberUseCase.Generate"},
				},
				"sum exceeds the maximum int64 value")
	}

	uid, err := use.GenerateUID.GetUIDFromNum(int64(sum))

	if err != nil {
		return "", err
	}

	return uid, nil
}
