import { execSync } from 'node:child_process';
import path from 'node:path';
import { createDb } from '@pintrush/db';

export const TEST_DB_NAME = 'pintrush_test_gs';
export const TEST_DB_URL = `postgresql://pintrush:pintrush@localhost:54329/${TEST_DB_NAME}`;

/**
 * A database of its own so game-server tests never race the db package's tests. Setup is
 * non-destructive: the schema is pushed (additive), every test file seeds uniquely named venues,
 * and sessions left live by earlier runs are closed so crash-recovery tests only see their own.
 */
export default async function setup() {
  const admin = createDb('postgresql://pintrush:pintrush@localhost:54329/postgres');
  try {
    const rows = await admin.$queryRawUnsafe<{ n: number }[]>(`select count(*)::int as n from pg_database where datname = '${TEST_DB_NAME}'`);
    if (!rows[0]?.n) {
      // Explicit UTF8: on Windows an old local cluster may default to WIN1252.
      await admin.$executeRawUnsafe(`create database ${TEST_DB_NAME} with template template0 encoding 'UTF8' lc_collate 'C' lc_ctype 'C'`);
    }
  } finally {
    await admin.$disconnect();
  }
  execSync('npx prisma db push', {
    cwd: path.resolve(import.meta.dirname, '../../../packages/db'),
    env: { ...process.env, DATABASE_URL: TEST_DB_URL },
    stdio: 'pipe',
  });
  const db = createDb(TEST_DB_URL);
  try {
    await db.gameSession.updateMany({ where: { status: { in: ['WAITING', 'RUNNING', 'PAUSED'] } }, data: { status: 'COMPLETED' } });
  } finally {
    await db.$disconnect();
  }
}
