import { redirect } from "next/navigation"
import Link from "next/link"
import { desc, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { api_keys } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { ApiKeyManager, type ApiKeyRow } from "@/components/dashboard/api-key-manager"

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

export default async function ApiKeysSettingsPage() {
  const user = await getSessionUser()
  if (!user) redirect("/login")

  const rows = await db
    .select({
      id: api_keys.id,
      name: api_keys.name,
      key_prefix: api_keys.key_prefix,
      created_at: api_keys.created_at,
      last_used_at: api_keys.last_used_at,
      revoked_at: api_keys.revoked_at,
    })
    .from(api_keys)
    .where(eq(api_keys.user_id, user.id))
    .orderBy(desc(api_keys.created_at))

  const keys: ApiKeyRow[] = rows

  return (
    <div className="max-w-2xl space-y-6">
      <div>
        <h2 className="text-lg font-semibold text-white">API Keys</h2>
        <p className="text-sm text-white/40">
          Create keys to authenticate with the public REST API. See the{" "}
          <Link
            href="/api-docs"
            className="text-indigo-400 underline underline-offset-2 transition hover:text-indigo-300"
          >
            API documentation
          </Link>{" "}
          for available endpoints.
        </p>
      </div>
      <ApiKeyManager initialKeys={keys} />
    </div>
  )
}
