package threads

import (
	"context"
	"strings"

	threadsDomain "apps/backend/internal/module/threads/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *ThreadsOAuthCallbackLogic) ThreadsOAuthCallback(req *types.ThreadsOAuthCallbackReq) (*types.ThreadsOAuthCallbackData, error) {
	if l.svcCtx.Threads == nil {
		// 相對路徑：讓瀏覽器留在目前站台，而不是被丟到某台機器的 loopback。
		redir := strings.TrimRight(l.svcCtx.Config.PublicWebBase, "/") + "/app/crew?oauth=error&msg=not_configured"
		return &types.ThreadsOAuthCallbackData{Ok: false, Message: "not configured", RedirectUrl: redir}, nil
	}
	_, err := l.svcCtx.Threads.OAuthCallback(l.ctx, req.Code, req.State, req.Error)
	if err != nil {
		msg := err.Error()
		if err == threadsDomain.ErrOAuthDenied {
			msg = "denied"
		}
		return &types.ThreadsOAuthCallbackData{
			Ok: false, Message: msg,
			RedirectUrl: l.svcCtx.Threads.WebRedirect(false, msg),
		}, nil // browser redirect; don't 500 on user deny
	}
	return &types.ThreadsOAuthCallbackData{
		Ok: true, Message: "connected",
		RedirectUrl: l.svcCtx.Threads.WebRedirect(true, ""),
	}, nil
}
