import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { cronUnauthorizedResponse, isCronRequestAuthorized } from "@/lib/cron-auth";

export const dynamic = 'force-dynamic';

// Simulated state for demonstration (in a real app, use DB or Redis to track last checked block)
let lastCheckedSlashingCount = 0;
let lastCheckedAgentCount = 0;

export async function GET(request: Request) {
  if (!isCronRequestAuthorized(request)) {
    return cronUnauthorizedResponse("Treasury Alert");
  }

  try {
    const alerts = [];

    // 1. Check for new Slashing Events (Income from penalties)
    const currentSlashingCount = await prisma.slashingEvent.count();
    if (currentSlashingCount > lastCheckedSlashingCount) {
      const newSlashings = await prisma.slashingEvent.findMany({
        orderBy: { created_at: "desc" },
        take: currentSlashingCount - lastCheckedSlashingCount
      });

      for (const slashing of newSlashings) {
        alerts.push(`🚨 [TREASURY ALERT - SLASHING] 
Agent ${slashing.agent_id} was penalized! 
💸 Amount Confiscated: ${(slashing.slashed_amount / 100).toFixed(2)} USDC
💼 Transferred to Platform Treasury.`);
      }
      lastCheckedSlashingCount = currentSlashingCount;
    }

    // 2. Check for new Premium Agents (Income from Staking)
    const currentPremiumCount = await prisma.agentProfile.count({
      where: { tier: "PREMIUM" }
    });

    if (currentPremiumCount > lastCheckedAgentCount) {
      const newPremium = await prisma.agentProfile.findMany({
        where: { tier: "PREMIUM" },
        orderBy: { updated_at: "desc" },
        take: currentPremiumCount - lastCheckedAgentCount
      });

      for (const agent of newPremium) {
        alerts.push(`🤑 [TREASURY ALERT - STAKE DEPOSIT] 
Agent ${agent.agent_id} has deposited stake!
💎 Tier Upgraded to PREMIUM
💰 TVL Increased by: 500 USDC`);
      }
      lastCheckedAgentCount = currentPremiumCount;
    }

    // 3. Dispatch Alerts
    if (alerts.length > 0) {
      console.log("================ TREASURY ALERTS ================");
      alerts.forEach(alert => console.log(alert));
      console.log("=================================================");
      
      // Here you would typically POST to a Discord/Telegram Webhook
      // await fetch(DISCORD_WEBHOOK_URL, { method: "POST", body: JSON.stringify({ content: alerts.join('\n\n') }) })
    }

    return NextResponse.json({
      success: true,
      new_alerts_count: alerts.length,
      alerts: alerts
    });

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