import { execFileSync } from 'node:child_process';
import { E2E } from '../../playwright.config';

/**
 * Direct access to the E2E database.
 *
 * Shelling out to `psql` rather than adding a `pg` dependency to the frontend
 * workspace: the suite needs a handful of reads and a cleanup delete, and a
 * driver in `emaui/package.json` would follow the frontend build around
 * forever for the sake of them.
 */
const PSQL_ENV = {
  ...process.env,
  PGPASSWORD: process.env.E2E_DB_PASSWORD ?? 'TradingTria@2090',
};

export function sql(query: string): string[][] {
  const out = execFileSync(
    'psql',
    [
      '-h', process.env.E2E_DB_HOST ?? 'localhost',
      '-p', process.env.E2E_DB_PORT ?? '5432',
      '-U', process.env.E2E_DB_USER ?? 'postgres',
      '-d', E2E.database,
      '-tAF', '\t',
      '-c', query,
    ],
    { env: PSQL_ENV, encoding: 'utf8' },
  );
  return out
    .split('\n')
    .filter((line) => line.trim() !== '')
    .map((line) => line.split('\t'));
}

/** First column of the first row, or null when the query found nothing. */
export function sqlValue(query: string): string | null {
  const rows = sql(query);
  return rows.length > 0 ? rows[0][0] : null;
}

/** Removes everything a run created, so the next run starts from the same place. */
export function deleteApplicant(email: string): void {
  const safe = email.replace(/'/g, "''");
  const userId = sqlValue(`SELECT id FROM iam.users WHERE email = '${safe}'`);
  if (!userId) return;

  sql(`
    DELETE FROM licenses WHERE holder_user_id = '${userId}';
    DELETE FROM license_applications WHERE applicant_user_id = '${userId}';
    DELETE FROM profile_operator_types
      WHERE profile_id IN (SELECT id FROM profiles WHERE user_id = '${userId}');
    DELETE FROM profiles WHERE user_id = '${userId}';
    DELETE FROM iam.notifications WHERE recipient_id = '${userId}';
    DELETE FROM iam.user_verifications WHERE user_id = '${userId}';
    DELETE FROM iam.user_credentials WHERE user_id = '${userId}';
    DELETE FROM iam.user_roles WHERE user_id = '${userId}';
    DELETE FROM iam.users WHERE id = '${userId}';
  `);
}
