'use strict';

const { Pool } = require('pg');
const fs = require('fs');
const path = require('path');
try { require('dotenv').config(); } catch {}

const pool = new Pool({
  user: process.env.DB_USER || 'postgres',
  password: process.env.DB_PASSWORD,
  host: process.env.DB_HOST || 'localhost',
  port: Number(process.env.DB_PORT || 5432),
  database: process.env.DB_NAME || 'jnm_homeschool_db'
});

function inlineIncludes(sql, directory) {
  return sql.replace(/^\\i\s+(.+)$/gm, (_, file) => {
    const target = path.resolve(directory, String(file).trim());
    return fs.readFileSync(target, 'utf8').replace(/^BEGIN;\s*/i, '').replace(/\s*COMMIT;\s*$/i, '');
  });
}

(async () => {
  const file = path.join(__dirname, 'v35-backend-test-gate.sql');
  const sql = inlineIncludes(fs.readFileSync(file, 'utf8'), __dirname);
  await pool.query(sql);
  console.log('PASS: V35 backend-test database tables and ownership controls are ready.');
})().catch(error => {
  console.error('FAIL: V35 database update failed:', error.message);
  process.exitCode = 1;
}).finally(async () => { try { await pool.end(); } catch {} });
