import { GiveawayCreateDashboardSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { createGiveawayDashboard, GiveawayCreateTimeoutError, listGiveaways } from '@/lib/module-configs/giveaways';
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 giveaways = await listGiveaways(guildId);
    return NextResponse.json({ giveaways });
  } 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 = GiveawayCreateDashboardSchema.parse(body);

    const giveaway = await createGiveawayDashboard(guildId, session.user.id, input);

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

    return NextResponse.json(giveaway, { status: 201 });
  } catch (error) {
    if (error instanceof GiveawayCreateTimeoutError) {
      return NextResponse.json({ error: error.message }, { status: 504 });
    }
    return toApiErrorResponse(error);
  }
}
