/**
 * Individual Campaign API Route
 * GET /api/seo-agents/campaigns/[id] - Get campaign state
 * POST /api/seo-agents/campaigns/[id] - Perform action (resume, pause)
 */

import { NextRequest, NextResponse } from 'next/server';
import { AuthMiddleware } from '@/lib/auth';

const LANGGRAPH_URL = process.env.LANGGRAPH_URL || 'http://127.0.0.1:8001';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // Require admin role
    const authResult = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResult instanceof NextResponse) {
      return authResult;
    }

    const { id } = await params;

    const res = await fetch(`${LANGGRAPH_URL}/api/campaigns/${id}/state`);

    if (!res.ok) {
      return NextResponse.json(
        { error: 'Campaign not found' },
        { status: res.status }
      );
    }

    const data = await res.json();
    return NextResponse.json(data);
  } catch (error) {
    console.error('[API] Campaign state error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch campaign state' },
      { status: 500 }
    );
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // Require admin role
    const authResult = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResult instanceof NextResponse) {
      return authResult;
    }

    const { id } = await params;
    const body = await request.json();
    const { action } = body;

    if (!action || !['resume', 'pause', 'cancel'].includes(action)) {
      return NextResponse.json(
        { error: 'Invalid action. Must be: resume, pause, or cancel' },
        { status: 400 }
      );
    }

    const res = await fetch(`${LANGGRAPH_URL}/api/campaigns/${id}/${action}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
    });

    if (!res.ok) {
      const errorData = await res.json().catch(() => ({}));
      return NextResponse.json(
        { error: errorData.detail || `Failed to ${action} campaign` },
        { status: res.status }
      );
    }

    const data = await res.json();
    return NextResponse.json(data);
  } catch (error) {
    console.error('[API] Campaign action error:', error);
    return NextResponse.json(
      { error: 'Failed to perform campaign action' },
      { status: 500 }
    );
  }
}
