import { SocialFeedDashboardCreateSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { createFeed, FeedPremiumError, listFeeds } from '@/lib/module-configs/feeds';
import { prisma } from '@/lib/prisma';

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

export async function GET(_request: NextRequest, { params }: RouteParams) {
  const { guildId } = await params;
  try {
    await requireGuildAccess(guildId);
    const feeds = await listFeeds(guildId);
    return NextResponse.json({ feeds });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function POST(request: NextRequest, { params }: RouteParams) {
  const { guildId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const body = await request.json();
    const input = SocialFeedDashboardCreateSchema.parse(body);

    const feed = await createFeed(guildId, input);

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

    return NextResponse.json(feed, { status: 201 });
  } catch (error) {
    if (error instanceof FeedPremiumError) {
      return NextResponse.json({ error: error.code }, { status: 403 });
    }
    return toApiErrorResponse(error);
  }
}
