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

export const runtime = "nodejs";

const INTERNAL_SECRET_HEADER = "x-internal-secret";

/**
 * POST /api/internal/marketplace/usage
 *
 * Called by the Python proxy after each marketplace billing event.
 * Writes one row to MarketplaceUsageEvent for the resolved user.
 * Protected by INTERNAL_MARKETPLACE_SECRET.
 *
 * Body: { api_key_id, request_id, device_id?, model, prompt_tokens, completion_tokens, price_cents?, timestamp? }
 * User is resolved via ApiKey.proxyKeyId = api_key_id; events without a known user are not stored.
 */
export async function POST(request: NextRequest) {
  const secret = request.headers.get(INTERNAL_SECRET_HEADER);
  const expected = process.env.INTERNAL_MARKETPLACE_SECRET;
  if (!expected || secret !== expected) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  let body: {
    api_key_id: string;
    request_id: string;
    device_id?: string | null;
    model: string;
    prompt_tokens?: number;
    completion_tokens?: number;
    price_cents?: number | null;
    timestamp?: string;
  };
  try {
    body = await request.json();
  } catch {
    return NextResponse.json(
      { error: "Invalid JSON body" },
      { status: 400 }
    );
  }

  const {
    api_key_id,
    request_id,
    device_id,
    model,
    prompt_tokens = 0,
    completion_tokens = 0,
    price_cents,
  } = body;
  if (!api_key_id || !request_id || !model) {
    return NextResponse.json(
      { error: "Missing required fields: api_key_id, request_id, model" },
      { status: 400 }
    );
  }

  const key = await db.apiKey.findUnique({
    where: { proxyKeyId: api_key_id },
    select: { userId: true },
  });
  if (!key) {
    return NextResponse.json(
      { ok: false, reason: "unknown_api_key" },
      { status: 200 }
    );
  }

  await db.marketplaceUsageEvent.create({
    data: {
      userId: key.userId,
      requestId: request_id,
      deviceId: device_id ?? null,
      model,
      promptTokens: prompt_tokens,
      completionTokens: completion_tokens,
      priceCents: price_cents ?? null,
    },
  });
  return NextResponse.json({ ok: true });
}
