import { NextRequest, NextResponse } from 'next/server'
import { compare } from 'bcryptjs'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { totpService } from '@/lib/services/totp-service'

/**
 * POST /api/v1/auth/2fa/backup-codes
 * Regenerate backup codes - requires password
 * Invalidates all previous backup codes
 */
export async function POST(request: NextRequest) {
  try {
    const session = await auth()

    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id: userId, userType } = session.user
    const body = await request.json()
    const { password } = body

    if (!password) {
      return NextResponse.json(
        { error: 'Password is required' },
        { status: 400 }
      )
    }

    // Get user/staff data
    let passwordHash: string | null = null
    let twoFactorEnabled = false

    if (userType === 'staff') {
      const staff = await prisma.staff.findUnique({
        where: { id: userId },
        select: {
          passwordHash: true,
          twoFactorEnabled: true,
        },
      })
      passwordHash = staff?.passwordHash ?? null
      twoFactorEnabled = staff?.twoFactorEnabled ?? false
    } else {
      const user = await prisma.user.findUnique({
        where: { id: userId },
        select: {
          passwordHash: true,
          twoFactorEnabled: true,
        },
      })
      passwordHash = user?.passwordHash ?? null
      twoFactorEnabled = user?.twoFactorEnabled ?? false
    }

    if (!twoFactorEnabled) {
      return NextResponse.json(
        { error: '2FA is not enabled. Enable 2FA first.' },
        { status: 400 }
      )
    }

    // Verify password
    if (!passwordHash) {
      return NextResponse.json(
        { error: 'User not found' },
        { status: 404 }
      )
    }

    const isValidPassword = await compare(password, passwordHash)
    if (!isValidPassword) {
      return NextResponse.json(
        { error: 'Invalid password' },
        { status: 400 }
      )
    }

    // Generate new backup codes
    const { plainCodes, hashedCodesJson } = await totpService.generateBackupCodes()

    // Store new backup codes
    if (userType === 'staff') {
      await prisma.staff.update({
        where: { id: userId },
        data: { backupCodesEnc: hashedCodesJson },
      })
    } else {
      await prisma.user.update({
        where: { id: userId },
        data: { backupCodesEnc: hashedCodesJson },
      })
    }

    return NextResponse.json({
      backupCodes: totpService.formatBackupCodes(plainCodes),
      message: 'New backup codes generated. Previous codes are now invalid.',
    })
  } catch (error) {
    console.error('Error regenerating backup codes:', error)
    return NextResponse.json(
      { error: 'Failed to regenerate backup codes' },
      { status: 500 }
    )
  }
}
