package threads_account

import (
	"net/http"

	"haixun-backend/internal/logic/threads_account"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

	"github.com/zeromicro/go-zero/rest/httpx"
)

func ThreadsOauthCallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.ThreadsOAuthCallbackQuery
		if err := httpx.Parse(r, &req); err != nil {
			http.Redirect(w, r, threads_account.OAuthFailureRedirect(svcCtx.Config.ThreadsOAuth.SuccessRedirect, err.Error()), http.StatusFound)
			return
		}

		l := threads_account.NewThreadsOAuthCallbackLogic(r.Context(), svcCtx)
		redirectURL, err := l.ThreadsOAuthCallback(&req)
		if err != nil {
			http.Redirect(w, r, threads_account.OAuthFailureRedirect(svcCtx.Config.ThreadsOAuth.SuccessRedirect, err.Error()), http.StatusFound)
			return
		}
		http.Redirect(w, r, redirectURL, http.StatusFound)
	}
}
