/**
 * Dev-only: truncate treatment and lab case data (preserves catalog tables).
 * Usage: npx ts-node prisma/reset-treatment-data.ts
 *
 * Safe to run before or after `prisma migrate deploy`: tables that do not yet
 * exist are skipped instead of throwing.
 */
import { PrismaClient } from '@prisma/client';
import { config } from 'dotenv';
import path from 'path';

const envPath = path.join(__dirname, '..', '.env');
config({ path: envPath });

if (process.env.NODE_ENV === 'production') {
  console.error('reset-treatment-data is not allowed in production');
  process.exit(1);
}

const prisma = new PrismaClient();

// FK-safe order: children before parents.
const TABLES_IN_ORDER = [
  'lab_case_task_status_events',
  'lab_case_comments',
  'lab_case_attachments',
  'lab_case_tasks',
  'lab_case_sends',
  'lab_case_tooth_prosthesis',
  'lab_case_details',
  'lab_cases',
  'treatment_detail_attachments',
  'treatment_details',
  'treatments',
  'appointments',
];

async function tableExists(table: string): Promise<boolean> {
  const rows = await prisma.$queryRawUnsafe<Array<{ exists: string | null }>>(
    `SELECT to_regclass('public."${table}"')::text AS exists`,
  );
  return rows[0]?.exists != null;
}

async function main() {
  console.log('Truncating treatment and lab case data...');

  const existing: string[] = [];
  for (const table of TABLES_IN_ORDER) {
    if (await tableExists(table)) {
      existing.push(table);
    } else {
      console.log(`  - skipping "${table}" (does not exist yet)`);
    }
  }

  if (existing.length === 0) {
    console.log('No target tables exist yet. Run `prisma migrate deploy` first.');
    return;
  }

  const targets = existing.map((t) => `"${t}"`).join(', ');
  await prisma.$executeRawUnsafe(`TRUNCATE TABLE ${targets} CASCADE`);

  console.log('Done.');
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
