import bcrypt from 'bcrypt';
import pg from 'pg';
import inquirer from 'inquirer';

const { Pool } = pg;
import { config as loadEnv } from 'dotenv';
import { fileURLToPath } from 'node:url';
import { dirname, resolve as resolvePath } from 'node:path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

loadEnv({ path: resolvePath(__dirname, '../.env') });

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: Number(process.env.DB_PORT) || 5432,
});

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

async function addUser() {
  try {
    const { username, password } = await promptUser();
    const hashedPassword = await bcrypt.hash(password, 10);

    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);
    }

    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);
    if (error.code) console.error('Error code:', error.code);
  } finally {
    await pool.end();
  }
}

addUser();
