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

/**
 * GET /api/v1/auth/2fa/status
 * Get 2FA status for the current user
 */
export async function GET(request: NextRequest) {
  try {
    const session = await auth()

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

    const { id: userId, userType } = session.user

    let twoFactorEnabled = false
    let twoFactorVerifiedAt: Date | null = null
    let backupCodesEnc: string | null = null

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

    const backupCodeCount = totpService.getBackupCodeCount(backupCodesEnc)

    return NextResponse.json({
      enabled: twoFactorEnabled,
      enabledAt: twoFactorVerifiedAt,
      backupCodesRemaining: backupCodeCount,
    })
  } catch (error) {
    console.error('Error getting 2FA status:', error)
    return NextResponse.json(
      { error: 'Failed to get 2FA status' },
      { status: 500 }
    )
  }
}
