import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import {
  requireApiAuthWithOrg,
  requireApiAuthWithPermission,
  handleApiError,
} from "@/lib/api-auth";

export async function GET() {
  try {
    const session = await requireApiAuthWithOrg();

    const locations = await prisma.location.findMany({
      where: { organizationId: session.user.orgId },
      include: {
        collectionDays: {
          select: {
            id: true,
            name: true,
            dayOfWeek: true,
            timeStart: true,
            timeEnd: true,
            isActive: true,
          },
          orderBy: { dayOfWeek: "asc" },
        },
      },
      orderBy: { createdAt: "asc" },
    });

    return NextResponse.json({ locations });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function POST(req: NextRequest) {
  try {
    const session = await requireApiAuthWithPermission("settings.edit");

    const { name, address } = await req.json();

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

    const location = await prisma.location.create({
      data: {
        name,
        address: address || null,
        organizationId: session.user.orgId,
      },
    });

    return NextResponse.json({ location });
  } catch (error) {
    return handleApiError(error);
  }
}
