import { NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { prisma } from '@/lib/db'
import bcrypt from 'bcryptjs'
import { rateLimit, getClientIp, rateLimitResponse } from '@/lib/rate-limit'

const changePwLimiter = rateLimit({ id: 'change-pw', max: 5, windowSeconds: 60 * 15 })

export async function POST(req: NextRequest) {
  try {
    const ip = getClientIp(req)
    const rl = changePwLimiter.check(ip)
    if (!rl.success) return rateLimitResponse(rl.resetAt)

    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })

    const { currentPassword, newPassword } = await req.json()

    if (!currentPassword || !newPassword) {
      return NextResponse.json({ error: 'Beide Felder sind erforderlich' }, { status: 400 })
    }

    if (newPassword.length < 8) {
      return NextResponse.json({ error: 'Neues Kennwort muss mindestens 8 Zeichen lang sein' }, { status: 400 })
    }

    const dbUser = await (prisma as any).user.findUnique({
      where: { id: user.id },
      select: { password: true },
    })

    if (!dbUser) {
      return NextResponse.json({ error: 'Benutzer nicht gefunden' }, { status: 404 })
    }

    const isValid = await bcrypt.compare(currentPassword, dbUser.password)
    if (!isValid) {
      return NextResponse.json({ error: 'Aktuelles Kennwort ist falsch' }, { status: 400 })
    }

    const hashedPassword = await bcrypt.hash(newPassword, 12)
    await (prisma as any).user.update({
      where: { id: user.id },
      data: { password: hashedPassword },
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Change password error:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}
