package auth

import (
	"context"
	"strings"

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

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

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

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

func (l *LoginLogic) Login(req *types.AuthLoginReq) (resp *types.AuthSessionData, err error) {
	loginID := strings.TrimSpace(req.LoginId)
	if loginID == "" {
		loginID = strings.TrimSpace(req.Email)
	}
	platform := req.Platform
	if platform == "" {
		platform = domain.PlatformPassword
	}
	m, pair, err := l.svcCtx.Auth.LoginPassword(l.ctx, loginID, req.Password, platform)
	if err != nil {
		return nil, err
	}
	m = ensureOnboarding(l.ctx, l.svcCtx, m)
	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
}
