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 organization = await prisma.organization.findUnique({
      where: { id: session.user.orgId },
      select: {
        id: true,
        name: true,
        slug: true,
        type: true,
        timezone: true,
        allowedDomains: true,
      },
    });

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

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

function slugify(name: string): string {
  return name
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

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

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

    const data: Record<string, unknown> = {};
    if (name) {
      data.name = name;
      data.slug = slugify(name);
    }
    if (type) data.type = type;
    if (timezone) data.timezone = timezone;
    if (Array.isArray(allowedDomains)) {
      data.allowedDomains = allowedDomains
        .map((d: string) => d.trim().toLowerCase())
        .filter(Boolean);
    }

    await prisma.organization.update({
      where: { id: session.user.orgId },
      data,
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    return handleApiError(error);
  }
}
