/**
 * Task Subscription API
 * POST - Subscribe user to task
 * DELETE - Unsubscribe user from task
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { subscribeToTask, unsubscribeFromTask } from '@/lib/autonomy/system-tasks';

export const dynamic = 'force-dynamic';

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ taskKey: string }> }
) {
  try {
    const { taskKey } = await params;
    const body = await request.json();
    const { userId, notifyOnSuccess, notifyOnFailure, notifyOnAlert, notifyChannels } = body;

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

    const task = await prisma.systemTask.findUnique({ where: { taskKey } });
    if (!task) {
      return NextResponse.json(
        { error: 'Task not found' },
        { status: 404 }
      );
    }

    await subscribeToTask(userId, task.id, {
      notifyOnSuccess,
      notifyOnFailure,
      notifyOnAlert,
      notifyChannels,
    });

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

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ taskKey: string }> }
) {
  try {
    const { taskKey } = await params;
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');

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

    const task = await prisma.systemTask.findUnique({ where: { taskKey } });
    if (!task) {
      return NextResponse.json(
        { error: 'Task not found' },
        { status: 404 }
      );
    }

    await unsubscribeFromTask(userId, task.id);

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