import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireAuth } from "@/lib/auth";
import { PermissionError } from "@/lib/permissions";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const user = await requireAuth();
    const { id } = await params;

    const collectionDay = await prisma.collectionDay.findFirst({
      where: {
        id,
        location: { organizationId: user.orgId },
      },
      include: {
        location: { select: { id: true, name: true } },
        _count: { select: { cards: true } },
      },
    });

    if (!collectionDay) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }

    return NextResponse.json(collectionDay);
  } catch (error) {
    if (error instanceof PermissionError) {
      return NextResponse.json({ error: error.message }, { status: 403 });
    }
    return NextResponse.json({ error: "Failed to fetch collection day" }, { status: 500 });
  }
}
