import { NextResponse } from "next/server";
import { getActiveAccountId } from "@/lib/account-context";
import { assertAccountOwnedByUser } from "@/lib/auth/accounts";
import { apiRouteErrorResponse } from "@/lib/auth/api";
import { requireSessionUser } from "@/lib/auth/session";
import { clearThreadsAuthForAccount } from "@/lib/threads-api";

export async function POST(request: Request) {
  try {
    const user = await requireSessionUser();
    const body = (await request.json().catch(() => ({}))) as { accountId?: string };
    const accountId = body.accountId ?? (await getActiveAccountId());
    if (!accountId) {
      return NextResponse.json({ error: "沒有可中斷的帳號" }, { status: 400 });
    }
    await assertAccountOwnedByUser(user.id, accountId);
    await clearThreadsAuthForAccount(accountId);
    return NextResponse.json({ success: true });
  } catch (error) {
    return apiRouteErrorResponse(error, "threads/disconnect");
  }
}
