import { SocialFeedDashboardUpdateSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { deleteFeed, updateFeed } from '@/lib/module-configs/feeds';
import { prisma } from '@/lib/prisma';

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

export async function PATCH(request: NextRequest, { params }: RouteParams) {
  const { guildId, feedId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const body = await request.json();
    const patch = SocialFeedDashboardUpdateSchema.parse(body);

    const updated = await updateFeed(guildId, feedId, patch);
    if (!updated) {
      return NextResponse.json({ error: 'Feed not found' }, { status: 404 });
    }

    await writeDashboardAudit(prisma, {
      guildId,
      actorUserId: session.user.id,
      action: 'feeds.update',
      path: `/dashboard/${guildId}/feeds`,
      after: updated
    });

    return NextResponse.json(updated);
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

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

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

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