/**
 * Change Password API Route
 *
 * POST /api/account/change-password - Change customer password
 *
 * Requires current password verification before allowing password change.
 * Protected by `requireCustomer()` — admins get a 403.
 */

import {
  requireCustomer,
  findCustomerById,
  updateCustomerPassword,
  verifyPassword,
  validatePassword,
  MIN_PASSWORD_LENGTH,
} from '@rovela-ai/sdk/auth/server'

/**
 * POST /api/account/change-password
 *
 * Changes the authenticated customer's password.
 * Requires current password for verification.
 *
 * Body: { currentPassword: string, newPassword: string }
 */
export async function POST(request: Request) {
  const guard = await requireCustomer()
  if (!guard.ok) return guard.response

  try {
    const body = await request.json()
    const { currentPassword, newPassword } = body as {
      currentPassword?: string
      newPassword?: string
    }

    // Validate required fields
    if (!currentPassword || typeof currentPassword !== 'string') {
      return Response.json(
        { error: 'Current password is required' },
        { status: 400 }
      )
    }

    if (!newPassword || typeof newPassword !== 'string') {
      return Response.json(
        { error: 'New password is required' },
        { status: 400 }
      )
    }

    // Validate new password strength
    const passwordValidation = validatePassword(newPassword)
    if (!passwordValidation.valid) {
      return Response.json(
        { error: passwordValidation.error || `Password must be at least ${MIN_PASSWORD_LENGTH} characters` },
        { status: 400 }
      )
    }

    // Check that new password is different from current
    if (currentPassword === newPassword) {
      return Response.json(
        { error: 'New password must be different from current password' },
        { status: 400 }
      )
    }

    // Fetch customer to get current password hash
    const customer = await findCustomerById(guard.customer.id)

    if (!customer) {
      return Response.json(
        { error: 'Customer not found' },
        { status: 404 }
      )
    }

    // Verify current password
    const isCurrentPasswordValid = await verifyPassword(
      currentPassword,
      customer.passwordHash
    )

    if (!isCurrentPasswordValid) {
      return Response.json(
        { error: 'Current password is incorrect' },
        { status: 400 }
      )
    }

    // Update password
    await updateCustomerPassword(guard.customer.id, newPassword)

    return Response.json({
      success: true,
      message: 'Password changed successfully',
    })
  } catch (error) {
    console.error('[Change Password API] Failed to change password:', error)
    return Response.json(
      { error: 'Failed to change password' },
      { status: 500 }
    )
  }
}
