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

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

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

export async function POST(req: NextRequest) {
  try {
    const user = await requireAuth("settings.edit");
    if (!user.orgId) {
      return NextResponse.json({ error: "No organization" }, { status: 400 });
    }

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

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

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

    return NextResponse.json(location, { status: 201 });
  } catch (error) {
    if (error instanceof PermissionError) {
      return NextResponse.json({ error: error.message }, { status: 403 });
    }
    return NextResponse.json({ error: "Failed to create location" }, { status: 500 });
  }
}
