import { requireUserSession } from '../../../utils/auth.ts'
import { useDB } from '../../../utils/database.ts'
import { account } from '../../../database/schema/auth.ts'
import { eq, and } from 'drizzle-orm'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../../utils/errors'

interface DeleteAccountResponse {
  accountId: string
  message: string
}

export default defineEventHandler(async (event) => {
  try {
    const session = await requireUserSession(event)

    // Get account ID from route params
    const accountId = getRouterParam(event, 'id')

    if (!accountId) {
      throw ApiErrors.validationError('Account ID is required')
    }

    const db = useDB()

    // First, verify the account belongs to the user
    const existingAccount = await db
      .select()
      .from(account)
      .where(and(
        eq(account.id, accountId),
        eq(account.userId, session.user.id)
      ))
      .limit(1)

    if (!existingAccount || existingAccount.length === 0) {
      throw ApiErrors.notFound('Account not found or does not belong to you')
    }

    // Check total number of connected accounts for this user
    const allUserAccounts = await db
      .select()
      .from(account)
      .where(eq(account.userId, session.user.id))

    // Prevent deletion if this is the last connected account
    if (allUserAccounts.length <= 1) {
      throw ApiErrors.badRequest('Cannot disconnect your last authentication method. Please connect another account first.')
    }

    // Delete the account
    await db
      .delete(account)
      .where(and(
        eq(account.id, accountId),
        eq(account.userId, session.user.id)
      ))

    return createSuccessResponse<DeleteAccountResponse>({
      accountId,
      message: 'Account disconnected successfully'
    })
  } catch (error) {
    throw handleApiError(error)
  }
})
