import { createHash, randomBytes } from "crypto"
import { eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { api_keys } from "@/lib/db/schema"
import { getAccountContext } from "@/lib/account"

// ============================================================================
// Public API authentication (Bearer API keys for /api/v1).
//
// Keys look like `pmn_live_<48 hex chars>`. We persist ONLY the SHA-256 hash;
// the plaintext is returned once at creation and never stored. Lookups hash the
// presented token and match on the unique key_hash column.
// ============================================================================

const KEY_PREFIX = "pmn_live_"

/** Generate a new API key. Returns the one-time plaintext plus what to store. */
export function generateApiKey(): { plaintext: string; hash: string; prefix: string } {
  const secret = randomBytes(24).toString("hex") // 48 hex chars
  const plaintext = `${KEY_PREFIX}${secret}`
  return {
    plaintext,
    hash: hashApiKey(plaintext),
    // Non-secret display identifier, e.g. "pmn_live_ab12cd34…"
    prefix: `${KEY_PREFIX}${secret.slice(0, 8)}…`,
  }
}

export function hashApiKey(key: string): string {
  return createHash("sha256").update(key).digest("hex")
}

/** Extract a Bearer token from the Authorization header, or null. */
function bearerToken(request: Request): string | null {
  const header = request.headers.get("authorization") ?? ""
  const m = /^Bearer\s+(.+)$/i.exec(header.trim())
  const token = m?.[1]?.trim()
  return token ? token : null
}

export type ApiContext = {
  /** The user the API key belongs to. */
  userId: string
  /** Whose portfolio to scope data by (team-aware). */
  ownerId: string
  /** False for viewer-role memberships. */
  canWrite: boolean
}

/**
 * Resolve an incoming API request to its account context, or null if the
 * Bearer key is missing/invalid/revoked. Also best-effort stamps last_used_at.
 * Data queries MUST scope by the returned `ownerId`, mirroring the session
 * routes' use of getEffectiveOwnerId.
 */
export async function resolveApiRequest(request: Request): Promise<ApiContext | null> {
  const token = bearerToken(request)
  if (!token) return null

  const row = await db.query.api_keys.findFirst({
    where: eq(api_keys.key_hash, hashApiKey(token)),
    columns: { id: true, user_id: true, revoked_at: true },
  })
  if (!row || row.revoked_at) return null

  // Best-effort usage timestamp; never block the request on it.
  try {
    await db
      .update(api_keys)
      .set({ last_used_at: new Date().toISOString() })
      .where(eq(api_keys.id, row.id))
  } catch {
    /* ignore */
  }

  const ctx = await getAccountContext(row.user_id)
  return { userId: row.user_id, ownerId: ctx.ownerId, canWrite: ctx.canWrite }
}
