"use server"

import { revalidatePath } from "next/cache"
import { and, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { api_keys } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { generateApiKey } from "@/lib/api-auth"

// ============================================================================
// API key management (dashboard, session-authed — NOT api-key authed).
//
// We store ONLY the SHA-256 hash of each key; the plaintext is returned exactly
// once from createApiKey and is never persisted. Every query is scoped to the
// session user's id so one user can never touch another user's keys.
// ============================================================================

const SETTINGS_PATH = "/settings/api-keys"

/**
 * Create a new API key for the signed-in user. Returns the one-time plaintext
 * (show it once, then it's gone) plus the non-secret display prefix.
 */
export async function createApiKey(
  name: string
): Promise<{ plaintext: string; prefix: string }> {
  const user = await getSessionUser()
  if (!user) throw new Error("Unauthorized")

  const trimmed = typeof name === "string" ? name.trim() : ""
  if (!trimmed) throw new Error("Key name is required")
  if (trimmed.length > 100) throw new Error("Key name must be 100 characters or fewer")

  const { plaintext, hash, prefix } = generateApiKey()

  await db.insert(api_keys).values({
    user_id: user.id,
    name: trimmed,
    key_hash: hash,
    key_prefix: prefix,
  })

  revalidatePath(SETTINGS_PATH)
  return { plaintext, prefix }
}

/**
 * Revoke one of the signed-in user's keys. Scoped by user_id so a user can
 * never revoke another user's key. Idempotent: re-revoking is a no-op.
 */
export async function revokeApiKey(id: string): Promise<void> {
  const user = await getSessionUser()
  if (!user) throw new Error("Unauthorized")

  if (typeof id !== "string" || !id) throw new Error("Invalid key id")

  await db
    .update(api_keys)
    .set({ revoked_at: new Date().toISOString() })
    .where(and(eq(api_keys.id, id), eq(api_keys.user_id, user.id)))

  revalidatePath(SETTINGS_PATH)
}
