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

export const runtime = "nodejs";

const INTERNAL_SECRET_HEADER = "x-internal-secret";

/**
 * POST /api/internal/marketplace/auto-remove
 *
 * Called by the Python probe loop after each probe cycle to disable marketplace
 * participation for nodes whose 30-day uptime has fallen below the removal
 * threshold. Protected by INTERNAL_MARKETPLACE_SECRET.
 *
 * Body: { device_ids: string[] }
 * Response: { disabled: number, device_ids: string[] }
 */
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: { device_ids?: unknown };
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }

  const { device_ids } = body;
  if (!Array.isArray(device_ids) || device_ids.length === 0) {
    return NextResponse.json(
      { error: "device_ids must be a non-empty array" },
      { status: 400 },
    );
  }

  const ids = device_ids.filter((id): id is string => typeof id === "string");
  if (ids.length === 0) {
    return NextResponse.json(
      { error: "No valid string device IDs provided" },
      { status: 400 },
    );
  }

  const result = await db.device.updateMany({
    where: { id: { in: ids }, marketplaceEnabled: true },
    data: { marketplaceEnabled: false },
  });

  logger.info(
    { device_ids: ids, disabled: result.count },
    "marketplace_auto_remove",
  );

  return NextResponse.json({ disabled: result.count, device_ids: ids });
}
