import { initDatabase, AppDataSource, Work, PlatformAccount } from '../models/index.js';
import { logger } from '../utils/logger.js';

async function main() {
  const arg = process.argv[2];
  if (!arg) {
    logger.error('请提供账号ID（数据库主键）');
    logger.info('用法: tsx src/scripts/list-works-for-account.ts <accountId>');
    process.exit(1);
  }

  const accountId = Number(arg);
  if (!Number.isInteger(accountId) || accountId <= 0) {
    logger.error(`无效的账号ID: ${arg}`);
    process.exit(1);
  }

  try {
    await initDatabase();
    const accountRepo = AppDataSource.getRepository(PlatformAccount);
    const workRepo = AppDataSource.getRepository(Work);

    const account = await accountRepo.findOne({ where: { id: accountId } });
    if (!account) {
      logger.error(`未找到账号 ID=${accountId}`);
      process.exit(1);
    }

    logger.info(
      `账号: ID=${account.id}, platform=${account.platform}, accountId=${account.accountId}, name=${account.accountName}`
    );

    const works = await workRepo.find({
      where: { accountId: account.id },
      order: { publishTime: 'DESC' },
    });

    logger.info(`共找到 ${works.length} 条作品记录`);
    works.forEach((w, idx) => {
      logger.info(
        `${idx + 1}. id=${w.id}, platformVideoId=${w.platformVideoId}, title=${w.title}, play=${w.playCount}, like=${w.likeCount}`
      );
    });

    process.exit(0);
  } catch (e) {
    logger.error('执行失败:', e);
    process.exit(1);
  }
}

void main();

