import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, apiKeys, eq } from "@epicure/db";
import { ApiKeysManager } from "@/components/settings/api-keys-manager";

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

export default async function ApiKeysPage() {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) return null;

  const keys = await db
    .select({
      id: apiKeys.id,
      name: apiKeys.name,
      lastUsedAt: apiKeys.lastUsedAt,
      createdAt: apiKeys.createdAt,
    })
    .from(apiKeys)
    .where(eq(apiKeys.userId, session.user.id));

  return (
    <div className="space-y-8">
      <section className="rounded-xl border p-6 space-y-4">
        <div>
          <h2 className="font-semibold text-lg">API Keys</h2>
          <p className="text-sm text-muted-foreground mt-1">
            Manage API keys for programmatic access to the Epicure API.
          </p>
        </div>
        <ApiKeysManager
          initialKeys={keys.map((k) => ({
            id: k.id,
            name: k.name,
            lastUsedAt: k.lastUsedAt ? k.lastUsedAt.toISOString() : null,
            createdAt: k.createdAt.toISOString(),
          }))}
        />
      </section>
    </div>
  );
}
