/**
 * Agent Insights API
 * 
 * Proactive observations and recommendations from agents.
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export const dynamic = 'force-dynamic';

// GET - Query insights
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const agentId = searchParams.get('agentId');
    const type = searchParams.get('type');
    const severity = searchParams.get('severity');
    const status = searchParams.get('status');
    const limit = parseInt(searchParams.get('limit') || '50');

    const where: any = {};
    if (agentId) where.agentId = agentId;
    if (type) where.type = type;
    if (severity) where.severity = severity;
    if (status) where.status = status;

    const insights = await prisma.agentInsight.findMany({
      where,
      orderBy: [
        { severity: 'desc' },
        { createdAt: 'desc' }
      ],
      take: limit
    });

    return NextResponse.json({
      success: true,
      insights,
      count: insights.length
    });
  } catch (error: any) {
    console.error('Error querying insights:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

// POST - Create insight
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      agentId,
      type,
      title,
      content,
      severity = 'info',
      confidence = 0.8,
      actionable = true,
      relatedData = {},
      tags = []
    } = body;

    if (!agentId || !type || !title || !content) {
      return NextResponse.json(
        { error: 'agentId, type, title, and content are required' },
        { status: 400 }
      );
    }

    const insight = await prisma.agentInsight.create({
      data: {
        agentId,
        type,
        title,
        content,
        severity,
        confidence,
        actionable,
        relatedData,
        tags
      }
    });

    return NextResponse.json({
      success: true,
      insight
    });
  } catch (error: any) {
    console.error('Error creating insight:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

// PATCH - Update insight (acknowledge, action, dismiss)
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { id, status, acknowledgedBy, actionTaken } = body;

    if (!id || !status) {
      return NextResponse.json(
        { error: 'id and status are required' },
        { status: 400 }
      );
    }

    const updateData: any = { status };

    if (status === 'acknowledged' && acknowledgedBy) {
      updateData.acknowledgedBy = acknowledgedBy;
      updateData.acknowledgedAt = new Date();
    }

    if (status === 'actioned' && actionTaken) {
      updateData.actionTaken = actionTaken;
    }

    const insight = await prisma.agentInsight.update({
      where: { id },
      data: updateData
    });

    return NextResponse.json({
      success: true,
      insight
    });
  } catch (error: any) {
    console.error('Error updating insight:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
