import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { getAgentInbox, sendAgentMessage } from '@/lib/agent-hierarchy/engine';

export const dynamic = 'force-dynamic';

/**
 * GET /api/agents/messages?agentId=xxx&status=pending
 * Get messages for a specific agent.
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const agentId = searchParams.get('agentId');
    const status = searchParams.get('status') || undefined;

    if (!agentId) {
      return NextResponse.json({ error: 'agentId is required' }, { status: 400 });
    }

    const messages = await getAgentInbox(agentId, status);
    return NextResponse.json({ messages });
  } catch (error) {
    console.error('Failed to fetch messages:', error);
    return NextResponse.json({ error: 'Failed to fetch messages' }, { status: 500 });
  }
}

/**
 * POST /api/agents/messages
 * Send a message from one agent to another.
 * Body: { fromAgentId, toAgentId, type, subject, content, priority }
 */
export async function POST(request: NextRequest) {
  try {
    const { fromAgentId, toAgentId, type, subject, content, priority } = await request.json();

    if (!fromAgentId || !toAgentId || !type || !subject || !content) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const message = await sendAgentMessage(fromAgentId, toAgentId, type, subject, content, priority);
    return NextResponse.json({ success: true, message });
  } catch (error) {
    console.error('Failed to send message:', error);
    return NextResponse.json({ error: 'Failed to send message' }, { status: 500 });
  }
}
