"use strict";

const {
  newPublishPage,
  detachPublishBrowser,
  closePublishBrowser,
} = require("./publish_browser.js");
const { publishToDouyin } = require("./publish_to_douyin.js");

const PLATFORM_LABELS = {
  douyin: "抖音",
  kuaishou: "快手",
  shipin: "视频号",
  xiaohongshu: "小红书",
};

async function publishToPlatform(platform, accountId, cookies, params) {
  const label = PLATFORM_LABELS[platform] || platform;
  if (platform === "douyin") {
    const page = await newPublishPage(platform, accountId, cookies);
    let result;
    try {
      result = await publishToDouyin(page, params);
      return result;
    } finally {
      const keepOpen =
        Boolean(params.keepPageOpen) ||
        Boolean(result?.keepPageOpen) ||
        result?.status === "manual_pending" ||
        result?.status === "verification_required";
      if (keepOpen) {
        globalThis.__native?.emitProgress?.(
          "浏览器已保留（独立进程），请在页面中检查并手动点击发布",
        );
        await detachPublishBrowser(platform, accountId);
      } else {
        try {
          await page.close();
        } catch {
          /* ignore */
        }
        await closePublishBrowser(platform, accountId);
      }
    }
  }
  return {
    success: false,
    status: "failed",
    message: `${label}自动发布即将支持，请先使用抖音`,
  };
}

module.exports = { publishToPlatform, PLATFORM_LABELS };
