// OAuth browser callback: redirect to FE (not JSON envelope).
package threads

import (
	"net/http"

	"apps/backend/internal/logic/threads"
	"apps/backend/internal/svc"
	"apps/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.ThreadsOAuthCallbackReq
		if err := httpx.Parse(r, &req); err != nil {
			http.Redirect(w, r, "/app/crew?oauth=error&msg=bad_request", http.StatusFound)
			return
		}
		l := threads.NewThreadsOAuthCallbackLogic(r.Context(), svcCtx)
		data, _ := l.ThreadsOAuthCallback(&req)
		if data != nil && data.RedirectUrl != "" {
			http.Redirect(w, r, data.RedirectUrl, http.StatusFound)
			return
		}
		http.Redirect(w, r, "/app/crew?oauth=error", http.StatusFound)
	}
}
