import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { adminUnauthorizedResponse, isAdminRequestAuthorized } from "@/lib/admin-auth";
import crypto from "crypto";

export const dynamic = 'force-dynamic';

const GOD_MODE_TOKEN = (process.env.GOD_MODE_TOKEN || "").trim();
const ENABLE_GOD_MODE_HARVEST = process.env.ENABLE_GOD_MODE_HARVEST === "true";

function isBreakGlassTokenMatched(token: string | null) {
  if (!GOD_MODE_TOKEN || !token) {
    return false;
  }

  const expected = Buffer.from(GOD_MODE_TOKEN);
  const actual = Buffer.from(token);
  return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
}

export async function POST(request: NextRequest) {
  if (!ENABLE_GOD_MODE_HARVEST) {
    return NextResponse.json({ error: "Break-glass harvest is disabled." }, { status: 404 });
  }

  if (!isAdminRequestAuthorized(request)) {
    return adminUnauthorizedResponse();
  }

  try {
    const breakGlassToken = request.headers.get("x-break-glass-token");
    if (!isBreakGlassTokenMatched(breakGlassToken)) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json().catch(() => ({}));
    if (body?.confirmation !== "ARCHIVE_OPEN_TASKS") {
      return NextResponse.json(
        { error: "Missing confirmation. Send confirmation=ARCHIVE_OPEN_TASKS." },
        { status: 400 }
      );
    }

    console.warn("[break-glass] Archiving open/executing tasks by admin request.");

    const harvestReport = await prisma.$transaction(async (tx) => {
      const allAgents = await tx.agentProfile.findMany();
      const totalStakedCents = allAgents.reduce((sum, agent) => sum + agent.staked_amount, 0);

      const openTasks = await tx.task.findMany({
        where: { status: { in: ["OPEN", "EXECUTING", "VERIFYING"] } }
      });
      const totalEscrowAtRisk = openTasks.reduce((sum, t) => sum + t.reward_amount, 0);

      await tx.task.updateMany({
        where: { status: { in: ["OPEN", "EXECUTING", "VERIFYING"] } },
        data: { status: "ARCHIVED" }
      });

      await tx.auditEvent.create({
        data: {
          actorType: "ADMIN",
          actorId: "break-glass",
          action: "BREAK_GLASS_ARCHIVE_TASKS",
          entityType: "SYSTEM",
          entityId: "god-mode-harvest",
          afterState: {
            archived_task_count: openTasks.length,
            affected_task_ids: openTasks.map((task) => task.id),
          },
          reason: "Manual break-glass archive requested with explicit confirmation.",
        },
      });

      return {
        total_staked_usd: totalStakedCents / 100,
        total_escrow_at_risk_usd: totalEscrowAtRisk / 100,
        archived_task_count: openTasks.length,
      };
    });

    return NextResponse.json({
      success: true,
      message: "Break-glass archive completed.",
      harvest_report: harvestReport
    });

  } catch (error: unknown) {
    console.error("[God Mode Error]", error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
