import { GiveawayActionSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import {
  endGiveawayDashboard,
  GiveawayEndError,
  setGiveawayPaused
} from '@/lib/module-configs/giveaways';
import { prisma } from '@/lib/prisma';

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

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

    let giveaway;
    if (action === 'end') {
      giveaway = await endGiveawayDashboard(guildId, giveawayId);
    } else if (action === 'pause') {
      giveaway = await setGiveawayPaused(guildId, giveawayId, true);
    } else {
      giveaway = await setGiveawayPaused(guildId, giveawayId, false);
    }

    if (!giveaway) {
      return NextResponse.json({ error: 'Giveaway not found or already ended' }, { status: 404 });
    }

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

    return NextResponse.json(giveaway);
  } catch (error) {
    if (error instanceof GiveawayEndError) {
      return NextResponse.json({ error: error.message }, { status: 502 });
    }
    return toApiErrorResponse(error);
  }
}
