package usecase

import (
	errs "backend/pkg/library/errors"
	"backend/pkg/member/domain/config"
	"backend/pkg/member/domain/repository"
	"backend/pkg/member/domain/usecase"
	repo "backend/pkg/member/repository"
	"context"
	"errors"
)

type MemberUseCaseParam struct {
	Account         repository.AccountRepository
	User            repository.UserRepository
	AccountUID      repository.AccountUIDRepository
	VerifyCodeModel repository.VerifyCodeRepository
	GenerateUID     repository.AutoIDRepository
	Config          config.Config
	Logger          errs.Logger
}

type MemberUseCase struct {
	MemberUseCaseParam
}

func MustMemberUseCase(param MemberUseCaseParam) usecase.AccountUseCase {
	return &MemberUseCase{
		param,
	}
}

func (use *MemberUseCase) FindLoginIDByUID(ctx context.Context, uid string) (usecase.BindingUser, error) {
	data, err := use.AccountUID.FindOneByUID(ctx, uid)
	if err != nil {
		if errors.Is(err, repo.ErrNotFound) {
			e := errs.ResNotFoundError("failed to find user by uid: " + uid)

			return usecase.BindingUser{}, e
		}

		e := errs.DBErrorErrorL(use.Logger,
			[]errs.LogField{
				{Key: "uid", Val: uid},
				{Key: "func", Val: "AccountUID.FindOneByUID"},
				{Key: "err", Val: err.Error()},
			},
			"failed to use database")

		return usecase.BindingUser{}, e
	}

	return usecase.BindingUser{
		UID:     data.UID,
		LoginID: data.LoginID,
	}, nil
}
