import type { Metadata } from "next";
import { requireAuth } from "@/lib/auth/guards";
import { subjectHasFeature } from "@/lib/billing/subscription";
import { prisma } from "@/lib/db";
import { PageHeader } from "@/components/app/page-header";
import { UpgradeGate } from "@/components/app/upgrade-gate";
import { ApiKeysClient } from "@/components/app/api-keys-client";

export const metadata: Metadata = { title: "API keys" };

export default async function ApiKeysPage() {
  const session = await requireAuth();
  const allowed = await subjectHasFeature(
    session.user.id,
    "api_access",
    session.session.activeOrganizationId
  );

  return (
    <>
      <PageHeader title="API keys" description="Programmatic access to the Podcast Distribution AI API." />
      {!allowed ? (
        <UpgradeGate
          title="API access is a Pro feature"
          description="Upgrade to Pro to create API keys and generate episodes programmatically."
          requiredPlan="Pro"
        />
      ) : (
        <ApiKeysClient
          keys={(
            await prisma.apiKey.findMany({
              where: { userId: session.user.id, revokedAt: null },
              orderBy: { createdAt: "desc" },
            })
          ).map((k) => ({
            id: k.id,
            name: k.name,
            prefix: k.prefix,
            lastUsedAt: k.lastUsedAt?.toISOString() ?? null,
            createdAt: k.createdAt.toISOString(),
          }))}
        />
      )}
    </>
  );
}
