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

function getWithdrawalMetadata(metadata: unknown) {
  if (typeof metadata !== "object" || metadata === null) {
    return null;
  }

  const value = metadata as { currency?: unknown; amount?: unknown };
  return {
    currency: typeof value.currency === "string" ? value.currency : null,
    amount: typeof value.amount === "number" ? value.amount : 0,
  };
}

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 });
    }

    // Calculate actual platform balance to ensure sufficient funds
    const completedTasks = await prisma.task.findMany({
      where: { status: "COMPLETED" },
      select: { reward_amount: true, reward_currency: true }
    });

    let totalUsdcRevenue = 0;
    let totalFiatRevenue = 0;

    for (const t of completedTasks) {
      const feeCut = t.reward_amount * 0.05; // 5% platform fee
      if (t.reward_currency === "USDC") {
        totalUsdcRevenue += feeCut;
      } else {
        totalFiatRevenue += feeCut;
      }
    }

    // Add revenue from Arbitrations (simulated)
    const arbitrations = await prisma.arbitration.count();
    totalUsdcRevenue += arbitrations * 5000; // 50 USDC court fee per arbitration

    // Get previous withdrawals
    const withdrawals = await prisma.auditEvent.findMany({
      where: { action: "TREASURY_WITHDRAWAL" }
    });

    for (const w of withdrawals) {
      const data = getWithdrawalMetadata(w.metadata);
      if (!data) continue;
      if (data.currency === "USDC") totalUsdcRevenue -= data.amount;
      else totalFiatRevenue -= data.amount;
    }

    // Validate balance
    if (type === "CRYPTO" && amount > totalUsdcRevenue) {
      return NextResponse.json({ error: "Insufficient USDC balance in Treasury" }, { status: 400 });
    }
    if (type === "FIAT" && amount > totalFiatRevenue) {
      return NextResponse.json({ error: "Insufficient Fiat balance in Treasury" }, { status: 400 });
    }

    // Simulate blockchain/stripe transfer latency
    await new Promise(resolve => setTimeout(resolve, 2000));

    // Record the withdrawal
    await prisma.auditEvent.create({
      data: {
        actorType: "ADMIN",
        actorId: "admin",
        action: "TREASURY_WITHDRAWAL",
        entityType: "TREASURY",
        entityId: "platform-treasury",
        metadata: {
          destination,
          type,
          amount,
          currency: type === "CRYPTO" ? "USDC" : "USD",
          txHash: type === "CRYPTO" ? "0x" + Math.random().toString(16).substring(2, 64) : `pi_${Math.random().toString(36).substring(2, 16)}`
        }
      }
    });

    return NextResponse.json({ 
      success: true, 
      message: `Successfully transferred ${(amount / 100).toFixed(2)} ${type === "CRYPTO" ? "USDC" : "USD"} to ${destination}`
    });

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