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) {
  try {
    const user = await requireAuth();
    if (!user.orgId) return NextResponse.json([]);

    const locationId = req.nextUrl.searchParams.get("locationId");

    const collectionDays = await prisma.collectionDay.findMany({
      where: {
        location: { organizationId: user.orgId },
        ...(locationId && { locationId }),
      },
      include: {
        location: { select: { id: true, name: true } },
        _count: { select: { cards: true } },
      },
      orderBy: { name: "asc" },
    });

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

export async function POST(req: NextRequest) {
  try {
    const user = await requireAuth("events.manage");

    const body = await req.json();
    const { locationId, name, description, rrule, dayOfWeek, timeStart, timeEnd, isRecurring, date } = body;

    if (!locationId || !name) {
      return NextResponse.json(
        { error: "Location and name are required" },
        { status: 400 }
      );
    }

    const location = await prisma.location.findFirst({
      where: { id: locationId, organizationId: user.orgId },
    });

    if (!location) {
      return NextResponse.json({ error: "Location not found" }, { status: 404 });
    }

    const collectionDay = await prisma.collectionDay.create({
      data: {
        locationId,
        name,
        description: description || null,
        rrule: rrule || null,
        dayOfWeek: dayOfWeek ?? null,
        timeStart: timeStart || null,
        timeEnd: timeEnd || null,
        isRecurring: isRecurring ?? true,
        date: date ? new Date(date) : null,
      },
    });

    return NextResponse.json(collectionDay, { status: 201 });
  } catch (error) {
    if (error instanceof PermissionError) {
      return NextResponse.json({ error: error.message }, { status: 403 });
    }
    console.error("[collection-days] Error:", error);
    return NextResponse.json({ error: "Failed to create collection day" }, { status: 500 });
  }
}
