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

async function main() {
  const arg = process.argv[2];
  if (!arg) {
    logger.error('请提供账号ID（platform_accounts 主键）');
    logger.info('用法: tsx src/scripts/delete-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' },
    });

    if (!works.length) {
      logger.info(`账号 ${account.id} 下没有作品记录，无需删除`);
      process.exit(0);
    }

    logger.info(`共找到 ${works.length} 条作品记录，将逐条删除（含关联的每日统计和评论）`);

    for (const work of works) {
      try {
        await workService.deleteWork(work.userId, work.id);
        logger.info(
          `已删除 work.id=${work.id}, platformVideoId=${work.platformVideoId}, title=${work.title}`
        );
      } catch (e) {
        logger.error(`删除 work.id=${work.id} 失败`, e);
      }
    }

    logger.info(`账号 ${account.id} 下的作品删除流程结束`);
    process.exit(0);
  } catch (e) {
    logger.error('执行失败:', e);
    process.exit(1);
  }
}

void main();

