/**
 * Single System Task API
 * GET - Get task details
 * PATCH - Update task (enable/disable, config)
 */

import { NextRequest, NextResponse } from 'next/server';
import { 
  getSystemTask, 
  setTaskEnabled, 
  updateTaskConfig,
  startTaskRun,
  completeTaskRun 
} from '@/lib/autonomy/system-tasks';

export const dynamic = 'force-dynamic';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ taskKey: string }> }
) {
  try {
    const { taskKey } = await params;
    const task = await getSystemTask(taskKey);

    if (!task) {
      return NextResponse.json(
        { error: 'Task not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({ task });
  } catch (error: any) {
    console.error('Error fetching task:', error);
    return NextResponse.json(
      { error: 'Failed to fetch task', details: error.message },
      { status: 500 }
    );
  }
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ taskKey: string }> }
) {
  try {
    const { taskKey } = await params;
    const body = await request.json();
    const { isEnabled, config, userId } = body;

    if (isEnabled !== undefined) {
      const success = await setTaskEnabled(taskKey, isEnabled, userId);
      if (!success) {
        return NextResponse.json(
          { error: 'Task not found' },
          { status: 404 }
        );
      }
    }

    if (config !== undefined) {
      const success = await updateTaskConfig(taskKey, config, userId);
      if (!success) {
        return NextResponse.json(
          { error: 'Task not found' },
          { status: 404 }
        );
      }
    }

    const task = await getSystemTask(taskKey);
    return NextResponse.json({ task });
  } catch (error: any) {
    console.error('Error updating task:', error);
    return NextResponse.json(
      { error: 'Failed to update task', details: error.message },
      { status: 500 }
    );
  }
}

// POST - Manually trigger task run
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ taskKey: string }> }
) {
  try {
    const { taskKey } = await params;
    const body = await request.json().catch(() => ({}));
    const { userId, input } = body;

    const runId = await startTaskRun(taskKey, 'manual', userId, input);

    if (!runId) {
      return NextResponse.json(
        { error: 'Task not found or not enabled' },
        { status: 404 }
      );
    }

    // In real implementation, this would trigger the actual task execution
    // For now, we'll simulate a quick completion
    await completeTaskRun(runId, 'success', {
      itemsProcessed: 0,
      data: { manual: true },
    });

    return NextResponse.json({
      message: 'Task triggered',
      runId,
    });
  } catch (error: any) {
    console.error('Error triggering task:', error);
    return NextResponse.json(
      { error: 'Failed to trigger task', details: error.message },
      { status: 500 }
    );
  }
}
