package usecase

import (
	"context"
	"math"

	"backend/pkg/member/domain"
	"backend/pkg/member/domain/entity"

	"backend/pkg/library/errs"
	"backend/pkg/library/errs/code"

	GIDLib "code.30cm.net/digimon/library-go/utils/invited_code"
	"github.com/zeromicro/go-zero/core/logx"
)

func (use *MemberUseCase) Generate(ctx context.Context) (string, error) {
	var data entity.AutoID
	err := use.GenerateUID.Inc(ctx, &data)
	if err != nil {
		e := errs.DatabaseErrorWithScopeL(
			code.CloudEPMember,
			domain.FailedToIncAccountErrorCode,
			logx.WithContext(ctx),
			[]logx.LogField{
				{Key: "func", Value: "AutoIDModel.Inc"},
				{Key: "err", Value: err.Error()},
			},
			"failed to inc account num").Wrap(err)

		return "", e
	}

	// 使用 uint64 處理，避免溢出
	sum := GIDLib.InitAutoID + data.Counter
	if sum > math.MaxInt64 {
		return "",
			errs.InvalidRangeWithScopeL(
				code.CloudEPMember,
				domain.FailedToIncAccountErrorCode,
				logx.WithContext(ctx),
				[]logx.LogField{
					{Key: "func", Value: "MemberUseCase.Generate"},
				},
				"sum exceeds the maximum int64 value")
	}

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

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

	return uid, nil
}
