import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { deleteScheduledMessageDashboard } from '@/lib/module-configs/scheduler';
import { prisma } from '@/lib/prisma';

interface RouteParams {
  params: Promise<{ guildId: string; scheduleId: string }>;
}

export async function DELETE(_request: NextRequest, { params }: RouteParams) {
  const { guildId, scheduleId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const deleted = await deleteScheduledMessageDashboard(guildId, scheduleId);
    if (!deleted) {
      return NextResponse.json({ error: 'Schedule not found' }, { status: 404 });
    }

    await writeDashboardAudit(prisma, {
      guildId,
      actorUserId: session.user.id,
      action: 'scheduler.delete',
      path: `/dashboard/${guildId}/scheduler`,
      before: { id: scheduleId }
    });

    return NextResponse.json({ ok: true });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
