"use server"
import { getSession } from "@auth0/nextjs-auth0"
import { CreateApiKeyDialog } from "./dialog-create-api-key"
import { Separator } from "@/components/ui/separator"
import { ApiKeyTable } from "./api-key-table"
import { type cf_api_keys, PrismaClient } from "@prisma/client"
import PostHogClient from "@/lib/posthog"
import { VS_CODE_KEY_NAME } from "@codeflash-ai/common"

const prisma = new PrismaClient()

interface ApiKeyWithOrg extends cf_api_keys {
  organization?: {
    id: string
    name: string
  } | null
  user?: {
    user_id: string
    github_username: string
    name: string | null
    email: string | null
  } | null
}

export default async function APIKeyGenerator(): Promise<JSX.Element> {
  const session = await getSession()
  // Auth handled by middleware + layout
  if (!session?.user) {
    throw new Error("Authentication required")
  }
  const userId = session.user.sub

  // Get user's organization memberships
  const userOrgMemberships = await prisma.organization_members.findMany({
    where: { user_id: userId },
    select: { organization_id: true },
  })
  const userOrgIds = userOrgMemberships.map(m => m.organization_id)

  // Fetch personal keys (no organization) and keys from user's organizations
  const apiKeys: ApiKeyWithOrg[] = await prisma.cf_api_keys.findMany({
    where: {
      OR: [
        { user_id: userId, organization_id: null },
        { organization_id: { in: userOrgIds } },
      ],
    },
    include: {
      organization: {
        select: { id: true, name: true },
      },
      user: {
        select: {
          user_id: true,
          github_username: true,
          name: true,
          email: true,
        },
      },
    },
    orderBy: { created_at: "desc" },
  })

  const posthog = PostHogClient()
  posthog?.capture({
    distinctId: userId,
    properties: { username: session.nickname },
    event: "webapp-loaded-api-keys",
  })

  await posthog?.shutdown()

  return (
    <div>
      <h3 className="scroll-m-20 text-2xl font-semibold tracking-tight max-w-full pb-1">
        API Keys
      </h3>
      <Separator />
      {apiKeys.length === 0 ? (
        <>
          <p className="leading-7 mt-6">
            Welcome! Check out the{" "}
            <a
              href="https://docs.codeflash.ai/getting-started/local-installation"
              target="_blank"
              className="underline"
            >
              Getting Started
            </a>{" "}
            docs, or create your first API key below to start using Codeflash.
          </p>
          <p>
            For help with setting up Codeflash on your codebase, please check out the Docs or{" "}
            <a
              href="https://calendly.com/codeflash-saurabh/codeflash-setup"
              target="_blank"
              className="underline"
            >
              book a call
            </a>{" "}
            with the founder.
          </p>
        </>
      ) : (
        <>
          {" "}
          <p className="leading-7 mt-6">
            These API keys are used to authenticate your requests to Codeflash&apos;s AI services.
          </p>
          <ApiKeyTable apiKeys={apiKeys} vscodeKeyName={VS_CODE_KEY_NAME} currentUserId={userId} />{" "}
        </>
      )}

      <CreateApiKeyDialog />
    </div>
  )
}
