const { Sequelize } = require('sequelize');
require('dotenv').config();

async function createDatabase() {
  // Connect to default postgres database first
  // Use credentials from .env or defaults
  const dbUser = process.env.DB_USER || 'postgres';
  const dbPassword = process.env.DB_PASSWORD || 'postgres';
  const dbHost = process.env.DB_HOST || 'localhost';
  const dbPort = process.env.DB_PORT || 5432;

  console.log(`🔌 Connecting to PostgreSQL at ${dbHost}:${dbPort} as user "${dbUser}"...`);

  const sequelize = new Sequelize('postgres', dbUser, dbPassword, {
    host: dbHost,
    port: dbPort,
    dialect: 'postgres',
    logging: false
  });

  try {
    await sequelize.authenticate();
    console.log('✅ Connected to PostgreSQL successfully');

    // Create the luckychit database
    console.log('🔄 Creating luckychit database...');
    await sequelize.query('CREATE DATABASE luckychit;');
    console.log('✅ Database "luckychit" created successfully');

    await sequelize.close();
    console.log('🎉 Database setup complete!');
    console.log('💡 You can now start the server with: npm run dev');
  } catch (error) {
    if (error.message.includes('already exists')) {
      console.log('✅ Database "luckychit" already exists');
      console.log('💡 You can now start the server with: npm run dev');
    } else {
      console.error('❌ Error creating database:', error.message);
    }
    await sequelize.close();
  }
}

createDatabase().catch(console.error);
