import { sql } from '@vercel/postgres';
import bcrypt from 'bcryptjs';
import { getUserFromRequest } from '../../../lib/permission-middleware';

export default async function handler(req, res) {
  if (req.method !== 'PUT') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    // Get authenticated user
    const user = await getUserFromRequest(req);
    if (!user) {
      return res.status(401).json({ error: 'Authentication required' });
    }

    const { current_password, new_password } = req.body;

    // Validate input
    if (!current_password || !new_password) {
      return res.status(400).json({ error: 'Current password and new password are required' });
    }

    if (new_password.length < 8) {
      return res.status(400).json({ error: 'New password must be at least 8 characters long' });
    }

    // Get current user password
    const userResult = await sql`
      SELECT password FROM users WHERE id = ${user.userId}
    `;

    if (userResult.rows.length === 0) {
      return res.status(404).json({ error: 'User not found' });
    }

    const currentHashedPassword = userResult.rows[0].password;

    // Verify current password
    const isCurrentPasswordValid = await bcrypt.compare(current_password, currentHashedPassword);
    if (!isCurrentPasswordValid) {
      return res.status(400).json({ error: 'Current password is incorrect' });
    }

    // Hash new password
    const saltRounds = 12;
    const newHashedPassword = await bcrypt.hash(new_password, saltRounds);

    // Update password
    await sql`
      UPDATE users 
      SET 
        password = ${newHashedPassword},
        updated_at = CURRENT_TIMESTAMP
      WHERE id = ${user.userId}
    `;

    res.status(200).json({ message: 'Password updated successfully' });

  } catch (error) {
    console.error('Password change error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
} 