import { NextResponse } from "next/server";
import { getOrCreateSettings } from "@/lib/user-settings";
import { getActiveAccountId } from "@/lib/account-context";
import { buildThreadsOAuthUrl, getAppBaseUrl, getThreadsAppId } from "@/lib/threads-api";

export async function GET(request: Request) {
  let homeUrl: URL;
  try {
    homeUrl = new URL("/", new URL(request.url).origin);
  } catch {
    return NextResponse.json({ error: "invalid request url" }, { status: 400 });
  }

  try {
    const settings = await getOrCreateSettings();
    const appId = getThreadsAppId();
    homeUrl = new URL("/", getAppBaseUrl(request, settings.appUrl));

    if (!appId) {
      homeUrl.searchParams.set(
        "threads_error",
        "系統尚未設定 Threads App，請管理員在 .env 填入 THREADS_APP_ID"
      );
      return NextResponse.redirect(homeUrl);
    }

    const accountId = await getActiveAccountId();
    if (!accountId) {
      homeUrl.searchParams.set("threads_error", "no_active_account");
      return NextResponse.redirect(homeUrl);
    }

    try {
      const url = buildThreadsOAuthUrl(request, appId, accountId, settings.appUrl);
      return NextResponse.redirect(url);
    } catch (err) {
      const message = err instanceof Error ? err.message : "invalid_app_id";
      homeUrl.searchParams.set("threads_error", message);
      return NextResponse.redirect(homeUrl);
    }
  } catch (err) {
    const message = err instanceof Error ? err.message : "authorize_failed";
    homeUrl.searchParams.set("threads_error", message);
    return NextResponse.redirect(homeUrl);
  }
}
