package auth

import (
	"context"

	"apps/backend/internal/module/member/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}

func (l *RegisterLogic) Register(req *types.AuthRegisterReq) (resp *types.AuthSessionData, err error) {
	m, pair, err := l.svcCtx.Auth.CreateUserAccount(l.ctx, domain.CreateLoginUserRequest{
		LoginID: req.Email, Platform: domain.PlatformPassword, AccountType: domain.AccountTypeEmail,
		Password: req.Password, DisplayName: req.DisplayName, Email: req.Email, Phone: req.Phone,
	})
	if err != nil {
		return nil, err
	}
	ids, _ := l.svcCtx.Auth.ListIdentities(l.ctx, m.UID)
	return &types.AuthSessionData{
		Tokens: types.TokenPairFromAuth(pair.AccessToken, pair.RefreshToken, pair.TokenType, pair.ExpiresIn),
		Member: *types.MemberFromModelWithIdentities(m, ids),
	}, nil
}
