"use server"
import { auth0 } from "@/lib/auth0"
import { redirect } from "next/navigation"
import {
  deleteAPIKeyById,
  genAndStoreAPITokenHashForVSC,
  safeGenAndStoreAPITokenHash,
  VS_CODE_KEY_NAME,
} from "@codeflash-ai/common"
import { TokenLimitExceededError } from "./token-error"
import { prisma } from "@/lib/prisma"
import { trackApiKeyCreated } from "@/lib/analytics/tracking"
import { updateTag } from "next/cache"

export async function generateToken(
  keyName: string,
  organizationId?: string,
): Promise<{ success: boolean; token: string | undefined; err: string | undefined }> {
  const user = await auth0.getSession()
  if (user == null) {
    redirect("/login")
  }
  const userId: string = user.user.sub

  try {
    const token: string = await safeGenAndStoreAPITokenHash(keyName, userId, organizationId)
    await trackApiKeyCreated(userId, { keyName, organizationId })
    updateTag(`apikeys:${userId}`)
    return { success: true, token, err: undefined }
  } catch (error) {
    if (error instanceof Error && error.message === "Token limit exceeded") {
      return { success: false, err: new TokenLimitExceededError().message, token: undefined }
    }
    if (
      error instanceof Error &&
      error.message === "User is not a member of the specified organization"
    ) {
      return { success: false, err: error.message, token: undefined }
    }
    return {
      success: false,
      err: "Failed to generate API key. Please try again.",
      token: undefined,
    }
  }
}
export async function generateTokenForVsCode(
  userId: string,
  orgId?: string,
): Promise<{
  success: boolean
  token: string | undefined
  err: string | undefined
}> {
  try {
    console.log("[Token] Generating VSCode API key for user:", userId, "orgId:", orgId)
    const token: string = await genAndStoreAPITokenHashForVSC(userId, orgId)
    updateTag(`apikeys:${userId}`)
    return { success: true, token, err: undefined }
  } catch (error) {
    if (error instanceof Error && error.message === "Token limit exceeded") {
      return { success: false, err: new TokenLimitExceededError().message, token: undefined }
    }
    return {
      success: false,
      err: "Failed to generate API key. Please try again.",
      token: undefined,
    }
  }
}
export async function deleteAPIKey(id: number): Promise<void> {
  const user = await auth0.getSession()
  if (user == null) {
    redirect("/login")
    return
  }
  const userId: string = user.user.sub

  // Security: Check if this is a VS Code extension key before deleting
  const keyToDelete = await prisma.cf_api_keys.findUnique({
    where: { id },
    select: { name: true, user_id: true },
  })

  if (!keyToDelete) {
    throw new Error("API key not found")
  }

  if (keyToDelete.user_id !== userId) {
    throw new Error("Unauthorized: You can only delete your own API keys")
  }

  if (keyToDelete.name === VS_CODE_KEY_NAME) {
    throw new Error("Cannot delete VS Code Extension API key")
  }

  await deleteAPIKeyById(id, userId)
  updateTag(`apikeys:${userId}`)
}
