require('dotenv').config({ path: '../.env' });
const bcrypt = require('bcrypt');
const { Pool } = require('pg');
const inquirer = require('inquirer');

// Log connection details for debugging (remove in production)
console.log('Attempting to connect with:', {
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  database: process.env.DB_NAME,
  port: process.env.DB_PORT
});

const pool = new Pool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  port: process.env.DB_PORT,
});

async function promptUser() {
  const questions = [
    {
      type: 'input',
      name: 'username',
      message: 'Enter username:',
      validate: (input) => {
        if (input.length < 3) {
          return 'Username must be at least 3 characters long';
        }
        return true;
      }
    },
    {
      type: 'password',
      name: 'password',
      message: 'Enter password:',
      mask: '*',
      validate: (input) => {
        if (input.length < 8) {
          return 'Password must be at least 8 characters long';
        }
        return true;
      }
    },
    {
      type: 'password',
      name: 'confirmPassword',
      message: 'Confirm password:',
      mask: '*',
      validate: (input, answers) => {
        if (input !== answers.password) {
          return 'Passwords do not match';
        }
        return true;
      }
    }
  ];

  return inquirer.prompt(questions);
}

async function addUser() {
  try {
    // Get user input
    const answers = await promptUser();
    const { username, password } = answers;

    // Hash password
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(password, saltRounds);

    // Check if user already exists
    const checkResult = await pool.query(
      'SELECT id FROM users WHERE username = $1',
      [username]
    );

    if (checkResult.rows.length > 0) {
      console.error('Error: Username already exists');
      process.exit(1);
    }

    // Insert new user
    const result = await pool.query(
      'INSERT INTO users (username, password) VALUES ($1, $2) RETURNING id',
      [username, hashedPassword]
    );

    console.log(`User ${username} created successfully with id ${result.rows[0].id}`);
  } catch (error) {
    console.error('Error creating user:', error);
    console.error('Error details:', error.message);
    if (error.code) {
      console.error('Error code:', error.code);
    }
  } finally {
    await pool.end();
  }
}

addUser(); 