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

const URLS = [
  "https://www.threads.com/search?q=備孕",
  "https://www.threads.com/search?q=備孕&serp_type=default",
  "https://www.threads.com/search?query=備孕",
  "https://www.threads.net/search?q=備孕",
  "https://www.threads.net/search?q=備孕&serp_type=default",
  "https://www.threads.com/",
];

async function main() {
  const account = await prisma.account.findFirst({ orderBy: { updatedAt: "desc" } });
  if (!account) return;

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

  for (const url of URLS) {
    try {
      await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30000 });
      await page.waitForTimeout(3000);
      const body = await page.locator("body").innerText();
      const articles = await page.locator('div[role="article"], a[href*="/post/"]').count();
      const preview = body.slice(0, 120).replace(/\n/g, " ");
      console.log("\n---");
      console.log("URL:", url);
      console.log("Final:", page.url());
      console.log("Articles/posts:", articles);
      console.log("Body:", preview);
    } catch (e) {
      console.log("FAIL", url, e instanceof Error ? e.message : e);
    }
  }

  await context.close();
}

main().catch(console.error);