import { Client } from 'pg';
import bcrypt from 'bcryptjs';
import dotenv from 'dotenv';

dotenv.config();

const client = new Client({
  connectionString: process.env.DATABASE_URL,
});

async function main() {
  await client.connect();

  const username = 'admin';
  const password = 'password123'; // Users should change this!
  const passwordHash = await bcrypt.hash(password, 10);

  try {
    // Check if user already exists
    const res = await client.query('SELECT id FROM users WHERE username = $1', [username]);
    if (res.rowCount && res.rowCount > 0) {
      console.log('Admin user already exists.');
    } else {
      await client.query(
        'INSERT INTO users (username, password_hash, role, created_at, updated_at) VALUES ($1, $2, $3, NOW(), NOW())',
        [username, passwordHash, 'admin']
      );
      console.log('Admin user created successfully.');
      console.log(`Username: ${username}`);
      console.log(`Password: ${password}`);
    }
  } catch (error) {
    console.error('Error creating admin user:', error);
  } finally {
    await client.end();
  }
}

main();
