import { getDb } from '../../utils/db.js'
import { requireAuth } from '../../utils/authHelpers.js'
import { hashPassword, verifyPassword } from '../../utils/password.js'

export default defineEventHandler(async (event) => {
  const currentUser = requireAuth(event)
  const body = await readBody(event).catch(() => ({}))
  const currentPassword = body?.currentPassword
  const newPassword = body?.newPassword

  if (typeof currentPassword !== 'string' || currentPassword.length < 1) {
    throw createError({ statusCode: 400, message: 'Current password is required' })
  }
  if (typeof newPassword !== 'string' || newPassword.length < 1) {
    throw createError({ statusCode: 400, message: 'New password cannot be empty' })
  }

  const { get, run } = await getDb()
  const user = await get(
    'SELECT id, password_hash, auth_provider FROM users WHERE id = ?',
    [currentUser.id],
  )
  if (!user) {
    throw createError({ statusCode: 404, message: 'User not found' })
  }
  const authProvider = user.auth_provider ?? 'local'
  if (authProvider !== 'local') {
    throw createError({
      statusCode: 400,
      message: 'Password change is only for local accounts. Use your identity provider to change password.',
    })
  }
  if (!verifyPassword(currentPassword, user.password_hash)) {
    throw createError({ statusCode: 400, message: 'Current password is incorrect' })
  }

  const passwordHash = hashPassword(newPassword)
  await run('UPDATE users SET password_hash = ? WHERE id = ?', [passwordHash, currentUser.id])
  return { ok: true }
})
