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

/**
 * POST /api/v1/auth/2fa/setup
 * Start 2FA setup - generates secret and returns QR code
 * Works for both customers and staff
 */
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, email } = session.user

    // Check if 2FA is already enabled
    let isAlreadyEnabled = false
    if (userType === 'staff') {
      const staff = await prisma.staff.findUnique({
        where: { id: userId },
        select: { twoFactorEnabled: true },
      })
      isAlreadyEnabled = staff?.twoFactorEnabled ?? false
    } else {
      const user = await prisma.user.findUnique({
        where: { id: userId },
        select: { twoFactorEnabled: true },
      })
      isAlreadyEnabled = user?.twoFactorEnabled ?? false
    }

    if (isAlreadyEnabled) {
      return NextResponse.json(
        { error: '2FA is already enabled. Disable it first to set up again.' },
        { status: 400 }
      )
    }

    // Generate new secret
    const secret = totpService.generateSecret()
    const encryptedSecret = totpService.encryptSecret(secret)

    // Store the secret temporarily (not enabled yet)
    if (userType === 'staff') {
      await prisma.staff.update({
        where: { id: userId },
        data: { twoFactorSecretEnc: encryptedSecret },
      })
    } else {
      await prisma.user.update({
        where: { id: userId },
        data: { twoFactorSecretEnc: encryptedSecret },
      })
    }

    // Generate QR code
    const qrCode = await totpService.generateQRCode(email!, secret)
    const otpauthUri = totpService.getOtpauthUri(email!, secret)

    return NextResponse.json({
      qrCode,
      secret, // Also return secret for manual entry
      otpauthUri,
    })
  } catch (error) {
    console.error('Error setting up 2FA:', error)
    return NextResponse.json(
      { error: 'Failed to set up 2FA' },
      { status: 500 }
    )
  }
}
