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/disable
 * Disable 2FA - requires password and either TOTP token or backup code
 */
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, token, backupCode } = body

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

    if (!token && !backupCode) {
      return NextResponse.json(
        { error: 'TOTP token or backup code is required' },
        { status: 400 }
      )
    }

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

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

    if (!twoFactorEnabled) {
      return NextResponse.json(
        { error: '2FA is not enabled' },
        { 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 }
      )
    }

    // Verify TOTP or backup code
    let isValid = false

    if (token && encryptedSecret) {
      const secret = totpService.decryptSecret(encryptedSecret)
      isValid = totpService.verifyToken(token, secret)
    } else if (backupCode && backupCodesEnc) {
      const result = await totpService.verifyBackupCode(backupCode, backupCodesEnc)
      isValid = result.valid
    }

    if (!isValid) {
      return NextResponse.json(
        { error: 'Invalid TOTP token or backup code' },
        { status: 400 }
      )
    }

    // Disable 2FA
    if (userType === 'staff') {
      await prisma.staff.update({
        where: { id: userId },
        data: {
          twoFactorEnabled: false,
          twoFactorSecretEnc: null,
          twoFactorVerifiedAt: null,
          backupCodesEnc: null,
        },
      })
    } else {
      await prisma.user.update({
        where: { id: userId },
        data: {
          twoFactorEnabled: false,
          twoFactorSecretEnc: null,
          twoFactorVerifiedAt: null,
          backupCodesEnc: null,
        },
      })
    }

    return NextResponse.json({
      disabled: true,
      message: '2FA has been disabled successfully.',
    })
  } catch (error) {
    console.error('Error disabling 2FA:', error)
    return NextResponse.json(
      { error: 'Failed to disable 2FA' },
      { status: 500 }
    )
  }
}
