import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";
import { recordBillingEvent } from "@/lib/marketplace-billing";

export const runtime = "nodejs";

const PLATFORM_FEE_PERCENT = 20;
const INTERNAL_SECRET_HEADER = "x-internal-secret";

/**
 * POST /api/internal/marketplace/billing
 *
 * Called by the Python proxy after forwarding a marketplace request.
 * Records the usage event and calculates revenue split (80% operator, 20% platform).
 * Protected by INTERNAL_MARKETPLACE_SECRET.
 *
 * Body: { operatorId, consumerId, deviceId, model, tokensIn, tokensOut, pricePerMToken, requestId }
 */
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: "Forbidden" }, { status: 403 });
  }

  let body: {
    operatorId: string;
    consumerId: string;
    deviceId: string;
    model: string;
    tokensIn?: number;
    tokensOut?: number;
    pricePerMToken?: number;
    requestId?: string;
  };
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }

  const { operatorId, consumerId, deviceId, model, tokensIn = 0, tokensOut = 0, pricePerMToken = 0.1 } = body;

  if (!operatorId || !consumerId || !deviceId || !model) {
    return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
  }

  const totalTokens = tokensIn + tokensOut;
  const revenue = (totalTokens / 1_000_000) * pricePerMToken;
  const operatorShare = revenue * (1 - PLATFORM_FEE_PERCENT / 100);
  const platformFee = revenue - operatorShare;
  const priceCents = Math.round(revenue * 100);

  try {
    // Record usage event for the consumer
    const event = await db.marketplaceUsageEvent.create({
      data: {
        userId: consumerId,
        requestId: body.requestId || `mkt_${Date.now()}`,
        deviceId,
        model,
        promptTokens: tokensIn,
        completionTokens: tokensOut,
        priceCents,
      },
    });

    // Record the 80/20 billing split event
    const billingEvent = await recordBillingEvent({
      deviceId,
      operatorId,
      buyerId: consumerId,
      model,
      promptTokens: tokensIn,
      completionTokens: tokensOut,
      priceCents,
    });

    logger.info(
      {
        usageEventId: event.id,
        billingEventId: billingEvent.id,
        operatorId,
        consumerId,
        revenue,
        operatorShare,
        model,
      },
      "marketplace_billing_recorded",
    );

    return NextResponse.json({
      eventId: event.id,
      billingEventId: billingEvent.id,
      revenue,
      operatorShare,
      platformFee,
    });
  } catch (error) {
    logger.error({ error }, "marketplace_billing_failed");
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}
