import { NextResponse } from 'next/server';
import { hash } from 'bcrypt';
import { Pool } from 'pg';

const pool = new Pool({
    connectionString: process.env.DATABASE_URL,
    idleTimeoutMillis: 1000,
    ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false
});

const SALT_ROUNDS = 10;

export async function POST(request: Request) {
  const { username, password } = await request.json();

  try {
    // Validate input
    if (!username || !password) {
      return NextResponse.json({ error: 'Username and password are required' }, { status: 400 });
    }

    console.log("checking...")
    const existingUser = await pool.query(
      'SELECT id FROM users WHERE username = $1',
      [username]
    );
    console.log(existingUser)
    if (existingUser.rows.length > 0) {
      return NextResponse.json({ error: 'Username already exists' }, { status: 409 });
    }

    // Hash the password
    const hashedPassword = await hash(password, SALT_ROUNDS);

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

    const userId = result.rows[0].id;

    return NextResponse.json({ success: true, userId }, { status: 201 });
  } catch (error) {
    console.error('Registration error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
