"use strict";

const { delay, newPublishPage, LOGIN_URLS } = require("./publish_browser.js");
async function checkDouyin(page) {
  await page.goto("https://creator.douyin.com/creator-micro/content/upload", {
    waitUntil: "domcontentloaded",
  });
  await delay(3000);
  const url = page.url();
  if (url.includes("login") || url.includes("passport")) {
    return { isLoggedIn: false };
  }
  const avatar = await page.$("#header-avatar");
  if (!avatar) return { isLoggedIn: false };
  let nickname = "";
  try {
    nickname = await page.$eval("#header-avatar", (el) => el.getAttribute("alt") || "");
  } catch {
    /* ignore */
  }
  return {
    isLoggedIn: true,
    userInfo: { nickname: nickname || "抖音用户", userId: "" },
  };
}

globalThis.__nodejsMain = async function main(params) {
  const p = params || {};
  const platform = String(p.platform || "").trim();
  const accountId = p.accountId || null;
  const cookies = Array.isArray(p.cookies) ? p.cookies : [];

  if (!LOGIN_URLS[platform]) {
    return { success: false, isLoggedIn: false, error: `不支持的平台: ${platform}` };
  }

  globalThis.__native?.emitProgress?.("正在检测登录状态…");
  const page = await newPublishPage(platform, accountId, cookies);
  try {
    let result;
    if (platform === "douyin") {
      result = await checkDouyin(page);
    } else {
      await page.goto(LOGIN_URLS[platform], { waitUntil: "domcontentloaded" });
      await delay(3000);
      const url = page.url();
      const loggedIn = !["login", "passport", "auth"].some((k) => url.includes(k));
      result = {
        isLoggedIn: loggedIn,
        userInfo: loggedIn ? { nickname: "已登录", userId: "" } : undefined,
      };
    }
    return {
      success: true,
      isLoggedIn: Boolean(result.isLoggedIn),
      userInfo: result.userInfo,
    };
  } catch (e) {
    return {
      success: false,
      isLoggedIn: false,
      message: e.message || String(e),
    };
  } finally {
    try {
      await page.close();
    } catch {
      /* ignore */
    }
  }
};
