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 org = await prisma.organization.findUnique({
      where: { id: user.orgId },
      include: {
        locations: { orderBy: { name: "asc" } },
        _count: { select: { members: true } },
      },
    });

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

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

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

    const org = await prisma.organization.update({
      where: { id: user.orgId },
      data: {
        ...(name !== undefined && { name }),
        ...(type !== undefined && { type }),
        ...(timezone !== undefined && { timezone }),
        ...(settings !== undefined && { settings }),
      },
    });

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