import pkg from 'pg';
import dotenv from 'dotenv';
import bcrypt from 'bcryptjs';

dotenv.config();

const { Client } = pkg;

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

  const username = 'admin';
  const plainPassword = 'password123';
  const passwordHash = await bcrypt.hash(plainPassword, 10);

  try {
    // Delete existing admin if any
    await client.query('DELETE FROM "users" WHERE "username" = $1', [username]);

    await client.query(`
      INSERT INTO "users" ("username", "password_hash", "role")
      VALUES ($1, $2, $3)
    `, [username, passwordHash, 'admin']);
    
    console.log(`Successfully created admin user: ${username} / ${plainPassword}`);
  } catch (e) {
    console.error('Error creating admin:', e.message);
  } finally {
    await client.end();
  }
}

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