import fs from 'fs';
import pkg from 'pg';
import dotenv from 'dotenv';
dotenv.config();

const { Client } = pkg;

async function main() {
  const client = new Client({
    connectionString: process.env.DATABASE_URL,
  });
  await client.connect();

  // Disable triggers to bypass foreign key checks temporarily
  await client.query("SET session_replication_role = replica;");

  const sql = fs.readFileSync('./sql/kitebeac_menu.sql', 'utf8');
  
  const lines = sql.split('\n');
  let currentInsert = '';
  let inInsert = false;
  let tableName = '';

  try {
    await client.query(`TRUNCATE TABLE "products", "categories", "users", "settings" RESTART IDENTITY CASCADE;`);
    console.log('Truncated existing tables');
  } catch (e) {
    console.log('Truncate skipped or failed (possibly tables empty)', e.message);
  }

  for (let line of lines) {
    if (line.startsWith('INSERT INTO')) {
      inInsert = true;
      currentInsert = line;
      let match = line.match(/INSERT INTO `(\w+)`/);
      if (match) {
        tableName = match[1];
      }
    } else if (inInsert) {
      currentInsert += '\n' + line;
    }

    if (inInsert && currentInsert.trim().endsWith(';')) {
      if (['categories', 'products', 'users', 'settings'].includes(tableName)) {
        let firstLineEnd = currentInsert.indexOf('VALUES') + 6;
        let prefix = currentInsert.substring(0, firstLineEnd).replace(/`/g, '"');
        let values = currentInsert.substring(firstLineEnd);
        
        values = values.replace(/\\'/g, "''");
        values = values.replace(/\\"/g, '"');
        
        if (tableName === 'users') {
          prefix = prefix.replace('"password"', '"password_hash"').replace('"email"', '"username"');
        }

        let query = prefix + values;

        // Skip settings because of id column mismatch, not crucial for menu data
        if (tableName !== 'settings') {
          try {
            await client.query(query);
            console.log(`Successfully inserted data into "${tableName}"`);
          } catch (e) {
            console.error(`Error inserting into "${tableName}":`, e.message);
          }
        }
      }
      inInsert = false;
      currentInsert = '';
    }
  }
  
  // Re-enable triggers
  await client.query("SET session_replication_role = origin;");
  
  await client.end();
}

main().catch(e => {
  console.error(e);
  process.exit(1);
});
