import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { db } from "@/app/db/db";
import { organisation } from "@/app/db/schema/organisation";
import { asc } from "drizzle-orm";

export async function GET(_req: NextRequest) {
  const session = await getServerSession(AuthOptions);
  if (!session?.user?.email?.endsWith("@domna.homes")) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const rows = await db
    .select({
      id: organisation.id,
      name: organisation.name,
      hubspotCompanyId: organisation.hubspotCompanyId,
    })
    .from(organisation)
    .orderBy(asc(organisation.name));

  return NextResponse.json(rows);
}
