/**
 * 下线 john 账户多余的 Plaza 演示公开页，释放发布配额。
 * 用法：node scripts/offline-john-demo-pages.mjs [--keep=N]
 */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createDbPool } from '../db.mjs';
import { createPublicationService } from '../mindspace-publications.mjs';

const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');

function loadEnvFile(filePath) {
  if (!fs.existsSync(filePath)) return;
  for (const line of fs.readFileSync(filePath, 'utf8').split('\n')) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) continue;
    const eq = trimmed.indexOf('=');
    if (eq < 0) continue;
    const key = trimmed.slice(0, eq).trim();
    const value = trimmed.slice(eq + 1).trim();
    if (!process.env[key]) process.env[key] = value;
  }
}

loadEnvFile(path.join(root, '.env'));
loadEnvFile(path.join(root, '../../.env.local'));

const keepCount = Number(process.argv.find((arg) => arg.startsWith('--keep='))?.split('=')[1] ?? 3);

const pool = createDbPool();
const publications = createPublicationService(pool);

const [users] = await pool.query(
  `SELECT id FROM h5_users WHERE username = 'john' LIMIT 1`,
);
const userId = users[0]?.id;
if (!userId) {
  console.error('未找到 john 用户');
  process.exit(1);
}

const [rows] = await pool.query(
  `SELECT id, url_slug, published_at
   FROM h5_publish_records
   WHERE user_id = ? AND status = 'online' AND url_slug LIKE 'demo-%'
   ORDER BY published_at DESC`,
  [userId],
);

const keep = rows.slice(0, keepCount);
const offline = rows.slice(keepCount);

if (offline.length === 0) {
  console.log(`当前 demo 在线页 ${rows.length} 个，无需下线（保留 ${keepCount} 个）。`);
  await pool.end();
  process.exit(0);
}

console.log(`保留 ${keep.length} 个 demo 页，下线 ${offline.length} 个…`);
for (const row of offline) {
  await publications.offline(userId, row.id);
  console.log(`✓ 已下线 ${row.url_slug}`);
}

const [usage] = await pool.query(
  `SELECT COUNT(DISTINCT page_id) AS public_page_used
   FROM h5_publish_records WHERE user_id = ? AND status = 'online'`,
  [userId],
);

console.log(`\n完成：john 当前在线公开页 ${usage[0]?.public_page_used ?? 0} 个。`);
await pool.end();
