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

export async function POST(request: NextRequest) {
  if (!isAdminRequestAuthorized(request)) {
    return adminUnauthorizedResponse();
  }

  try {
    const body = await request.json();
    const { destination, type, amount } = body;

    if (!destination || !type || !amount) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
    }

    const amountCents = Math.floor(Number(amount));
    if (!Number.isFinite(amountCents) || amountCents <= 0) {
      return NextResponse.json({ error: "Invalid amount" }, { status: 400 });
    }

    const snapshot = await getTreasurySnapshot();

    if (type === "CRYPTO" && amountCents > snapshot.available.usdc) {
      return NextResponse.json({ error: "Insufficient USDC balance in Treasury" }, { status: 400 });
    }
    if (type === "FIAT" && amountCents > snapshot.available.fiat) {
      return NextResponse.json({ error: "Insufficient Fiat balance in Treasury" }, { status: 400 });
    }

    await prisma.auditEvent.create({
      data: {
        actorType: "ADMIN",
        actorId: "admin",
        action: "TREASURY_WITHDRAWAL_REQUESTED",
        entityType: "TREASURY",
        entityId: "platform-treasury",
        metadata: {
          destination,
          type,
          amount: amountCents,
          currency: type === "CRYPTO" ? "USDC" : "USD",
          status: "PENDING_OPERATOR_EXECUTION",
        }
      }
    });

    return NextResponse.json({ 
      success: true, 
      message: `Withdrawal request recorded for ${(amountCents / 100).toFixed(2)} ${type === "CRYPTO" ? "USDC" : "USD"} to ${destination}. Execute the actual transfer from the treasury wallet or Stripe dashboard, then record the completed withdrawal.`
    });

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