import { prisma } from "../lib/db";
import { createContext } from "../lib/threads-browser/browser";

async function trySearch(label: string, prime: boolean) {
  const account = await prisma.account.findFirst({ orderBy: { updatedAt: "desc" } });
  if (!account) return;

  const context = await createContext(account.storageState, true);
  const page = await context.newPage();

  if (prime) {
    await page.goto("https://www.threads.com/", { waitUntil: "networkidle", timeout: 60000 });
    await page.waitForTimeout(2000);
  }

  const searchUrl = `https://www.threads.com/search?q=${encodeURIComponent("備孕")}&serp_type=default`;
  await page.goto(searchUrl, { waitUntil: "networkidle", timeout: 60000 });
  await page.waitForTimeout(3000);

  const body = await page.locator("body").innerText();
  const posts = await page.locator('a[href*="/post/"]').count();
  console.log(`[${label}] prime=${prime} posts=${posts} 404=${body.includes("走丟")} url=${page.url()}`);

  await context.close();
}

async function main() {
  await trySearch("direct", false);
  await trySearch("primed", true);
}

main().catch(console.error);