import type { PrismaClient } from '@prisma/client';
import { resolveSeedAccounts, resolveSeedMode, runSeed, type RunSeedOptions, type SeedMode } from './run-seed';

export type ResetSeedOptions = RunSeedOptions;

/** 清空 public 下除 _prisma_migrations 外的全部表（含用户、充值、注单、赛事等） */
export async function truncateApplicationTables(prisma: PrismaClient): Promise<void> {
  const rows = await prisma.$queryRaw<Array<{ tablename: string }>>`
    SELECT tablename
    FROM pg_tables
    WHERE schemaname = 'public'
      AND tablename <> '_prisma_migrations'
  `;

  const tableNames = rows.map((r) => `"${r.tablename}"`);
  if (tableNames.length === 0) return;

  await prisma.$executeRawUnsafe(
    `TRUNCATE TABLE ${tableNames.join(', ')} RESTART IDENTITY CASCADE`,
  );
}

function resolveResetSeedMode(options?: ResetSeedOptions): SeedMode {
  if (options?.mode) return options.mode;
  return resolveSeedMode();
}

/** 全量初始化：清表 + seed。production 模式仅保留 admin + WC2026 赛事目录。 */
export async function resetAndSeedDatabase(prisma: PrismaClient, options?: ResetSeedOptions) {
  const mode = resolveResetSeedMode(options);
  await truncateApplicationTables(prisma);
  await runSeed(prisma, { mode });
  return { seedMode: mode, demoAccounts: resolveSeedAccounts(mode) };
}
