package auth

import (
	"context"
	"strings"
	"time"

	domauth "gateway/internal/model/auth/domain/usecase"
	"gateway/internal/svc"
	"gateway/internal/types"

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

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

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

func (l *LoginSocialStartLogic) LoginSocialStart(req *types.LoginSocialStartReq) (*types.LoginSocialStartData, error) {
	if l.svcCtx.Zitadel == nil {
		return nil, errb.SysNotImplemented("zitadel not configured")
	}
	if l.svcCtx.AuthLoginSession == nil {
		return nil, errb.SysNotImplemented("login session not configured")
	}

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

	provider := strings.ToLower(strings.TrimSpace(req.Provider))
	ttl := time.Duration(l.svcCtx.Config.Auth.Defaults().RegistrationSessionTTLSeconds) * time.Second
	session, err := l.svcCtx.AuthLoginSession.Create(l.ctx, &domauth.CreateLoginSessionRequest{
		TenantID:    tenant.TenantID,
		TenantSlug:  tenant.Slug,
		Provider:    provider,
		RedirectURI: strings.TrimSpace(req.RedirectURI),
		TTL:         ttl,
	})
	if err != nil {
		return nil, err
	}

	oauthURL, err := l.svcCtx.Zitadel.AuthorizeURL(req.RedirectURI, loginOAuthState(session.SessionID), provider)
	if err != nil {
		return nil, wrapZitadelErr(err)
	}

	return &types.LoginSocialStartData{
		OauthURL:  oauthURL,
		SessionID: session.SessionID,
		ExpiresIn: session.ExpiresIn,
	}, nil
}
