import { ForbiddenException, Injectable } from '@nestjs/common';
import { PrismaService } from '../../shared/prisma/prisma.service';
import { DEMO_ACCOUNTS, runSeed } from './run-seed';

@Injectable()
export class DatabaseResetService {
  constructor(private prisma: PrismaService) {}

  isAllowed(): boolean {
    if (process.env.ALLOW_DB_RESET === 'true') return true;
    return process.env.NODE_ENV !== 'production';
  }

  async resetDatabase(): Promise<{ demoAccounts: readonly string[] }> {
    if (!this.isAllowed()) {
      throw new ForbiddenException('生产环境禁止重置数据库（需设置 ALLOW_DB_RESET=true）');
    }

    await this.truncateApplicationTables();
    await runSeed(this.prisma);

    return { demoAccounts: DEMO_ACCOUNTS };
  }

  private async truncateApplicationTables() {
    const rows = await this.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 this.prisma.$executeRawUnsafe(
      `TRUNCATE TABLE ${tableNames.join(', ')} RESTART IDENTITY CASCADE`,
    );
  }
}
