package auth

import (
	"context"
	"strings"

	"gateway/internal/svc"
	"gateway/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.LoginReq) (*types.LoginData, error) {
	if err := requireLoginDeps(l.svcCtx); err != nil {
		return nil, err
	}

	tenant, err := resolveTenant(l.ctx, l.svcCtx, req.TenantSlug)
	if err != nil {
		return nil, err
	}

	email := normalizeLoginEmail(req.Email)
	tok, err := l.svcCtx.Zitadel.VerifyPassword(l.ctx, email, req.Password)
	if err != nil {
		return nil, wrapZitadelErr(err)
	}

	identity, err := zitadelIdentityFromToken(l.ctx, l.svcCtx.Zitadel, tok)
	if err != nil {
		return nil, err
	}

	member, err := memberForLogin(l.ctx, l.svcCtx, tenant.TenantID, identity.Sub)
	if err != nil {
		return nil, err
	}
	if identity.Email != "" && !strings.EqualFold(strings.TrimSpace(member.ZitadelEmail), identity.Email) {
		// Prefer ZITADEL subject match; email mismatch is logged but does not block login.
		logx.WithContext(l.ctx).Infof("login: zitadel email mismatch for uid=%s", member.UID)
	}

	if member.TOTPEnrolled {
		return beginLoginMFA(l.ctx, l.svcCtx, tenant.TenantID, req.TenantSlug, member.UID)
	}

	tokens, err := issueAuthToken(l.ctx, l.svcCtx, tenant.TenantID, member.UID)
	if err != nil {
		return nil, err
	}
	return loginDataFromTokens(tokens), nil
}
