import { createHash } from "crypto";
import { prisma } from "@/lib/prisma";

export async function validateApiKey(bearerToken: string) {
  const keyHash = createHash("sha256").update(bearerToken).digest("hex");

  const apiKey = await prisma.apiKey.findFirst({
    where: { keyHash, revoked: false },
    include: {
      user: {
        include: {
          subscription: true,
        },
      },
    },
  });

  if (!apiKey) return null;

  prisma.apiKey
    .update({
      where: { id: apiKey.id },
      data: { lastUsedAt: new Date() },
    })
    .catch(() => {});

  return {
    userId: apiKey.userId,
    user: apiKey.user,
    subscription: apiKey.user.subscription,
    apiKey,
  };
}
