import jwt from 'jsonwebtoken';
import { sql } from '@vercel/postgres';
import { JWT_SECRET, JWT_TOKEN_TTL } from '../../lib/auth-secret.js';

export async function hashPassword(password) {
  const bcrypt = await import('bcryptjs');
  return await bcrypt.hash(password, 12);
}

export async function verifyPassword(password, hashedPassword) {
  const bcrypt = await import('bcryptjs');
  return await bcrypt.compare(password, hashedPassword);
}

export function generateToken(user) {
  return jwt.sign(
    {
      userId: user.id,
      email: user.email,
      role: user.role
    },
    JWT_SECRET,
    { expiresIn: JWT_TOKEN_TTL }
  );
}

export function verifyToken(token) {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch (error) {
    return null;
  }
}

export async function isAdmin(userId) {
  try {
    const result = await sql`
      SELECT role FROM users WHERE id = ${userId}
    `;
    return result.rows[0]?.role === 'admin';
  } catch (error) {
    console.error('Error checking admin status:', error);
    return false;
  }
}

export async function getUserById(userId) {
  try {
    const result = await sql`
      SELECT id, email, role, created_at FROM users WHERE id = ${userId}
    `;
    return result.rows[0];
  } catch (error) {
    console.error('Error getting user:', error);
    return null;
  }
}
