import { NextRequest } from "next/server";
import { db } from "@/lib/db";

interface ResolvedUser {
  id: string;
  email: string;
  name: string | null;
  plan: string;
}

/**
 * Resolve an API key from the Authorization header to a user.
 *
 * Supports:
 *   Authorization: Bearer lh_sk_...
 *
 * Returns null if the key is invalid, revoked, or expired.
 * Updates lastUsed on successful resolution.
 */
export async function resolveApiKeyUser(req: NextRequest): Promise<ResolvedUser | null> {
  const authHeader = req.headers.get("authorization");
  if (!authHeader) return null;

  const parts = authHeader.split(" ");
  if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") return null;

  const key = parts[1];
  if (!key.startsWith("lh_sk_")) return null;

  try {
    const apiKey = await db.apiKey.findUnique({
      where: { key },
      include: {
        user: {
          select: { id: true, email: true, name: true, plan: true },
        },
      },
    });

    if (!apiKey) return null;
    if (apiKey.revokedAt) return null;
    if (apiKey.expiresAt && new Date() > apiKey.expiresAt) return null;

    // Update lastUsed (fire-and-forget, don't block the request)
    db.apiKey.update({
      where: { id: apiKey.id },
      data: { lastUsed: new Date() },
    }).catch(() => { /* non-critical */ });

    return apiKey.user;
  } catch {
    return null;
  }
}
