import { NextRequest, NextResponse } from 'next/server'
import { auth, getSanitizedHeaders } from '@/lib/auth'
import { prisma } from '@innungsapp/shared'
// @ts-ignore
import { hashPassword } from 'better-auth/crypto'

export async function POST(req: NextRequest) {
  const session = await auth.api.getSession({ headers: await getSanitizedHeaders() })
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Nicht eingeloggt' }, { status: 401 })
  }

  const { newPassword } = await req.json()
  if (!newPassword || newPassword.length < 8) {
    return NextResponse.json({ error: 'Passwort muss mindestens 8 Zeichen haben.' }, { status: 400 })
  }

  const userId = session.user.id
  const newHash = await hashPassword(newPassword)

  const credAccount = await prisma.account.findFirst({
    where: { userId, providerId: 'credential' },
  })

  if (credAccount) {
    await prisma.account.update({ where: { id: credAccount.id }, data: { password: newHash } })
  } else {
    const { randomUUID } = await import('node:crypto')
    await prisma.account.create({
      data: { id: randomUUID(), accountId: userId, providerId: 'credential', userId, password: newHash },
    })
  }

  await prisma.user.update({ where: { id: userId }, data: { mustChangePassword: false } })

  return NextResponse.json({ success: true })
}
