import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { setActiveAccountForUser } from "@/lib/account-context";
import { apiRouteErrorResponse } from "@/lib/auth/api";
import { requireSessionUser } from "@/lib/auth/session";

/**
 * 準備一個「待綁定」的帳號並設為目前帳號，接著前端會導到官方 API 授權。
 */
export async function POST() {
  try {
    const user = await requireSessionUser();

    const existingUnbound = await prisma.account.findFirst({
      where: { userId: user.id, threadsUserId: null },
      orderBy: { updatedAt: "desc" },
      select: { id: true },
    });

    const accountId =
      existingUnbound?.id ??
      (
        await prisma.account.create({
          data: {
            userId: user.id,
            displayName: "待綁定帳號",
            storageState: "",
            valid: false,
          },
          select: { id: true },
        })
      ).id;

    await setActiveAccountForUser(user.id, accountId);

    return NextResponse.json({ accountId });
  } catch (error) {
    return apiRouteErrorResponse(error, "accounts/bind");
  }
}