package threads_account

import (
	"context"
	"net/url"
	"strings"

	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

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

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

func (l *ThreadsOAuthCallbackLogic) ThreadsOAuthCallback(req *types.ThreadsOAuthCallbackQuery) (string, error) {
	code := ""
	state := ""
	if req != nil {
		code = req.Code
		state = req.State
		if strings.TrimSpace(req.Error) != "" {
			msg := strings.TrimSpace(req.Error)
			if reason := strings.TrimSpace(req.ErrorReason); reason != "" {
				msg += " (" + reason + ")"
			}
			if desc := strings.TrimSpace(req.ErrorDescription); desc != "" {
				msg += ": " + desc
			}
			l.svcCtx.ThreadsAccount.RecordOAuthDebug("error", "meta_denied", "", msg)
			return failureRedirect(l.svcCtx.Config.ThreadsOAuth.SuccessRedirect, msg), nil
		}
	}
	result, err := l.svcCtx.ThreadsAccount.CompleteThreadsOAuthCallback(l.ctx, code, state)
	if err != nil {
		return failureRedirect(l.svcCtx.Config.ThreadsOAuth.SuccessRedirect, err.Error()), nil
	}
	return result.RedirectURL, nil
}

func failureRedirect(base, message string) string {
	base = strings.TrimSpace(base)
	if base == "" {
		base = "/"
	}
	sep := "?"
	if strings.Contains(base, "?") {
		sep = "&"
	}
	return base + sep + "threads_oauth=error&message=" + url.QueryEscape(message)
}

func OAuthFailureRedirect(successRedirect, message string) string {
	return failureRedirect(successRedirect, message)
}
