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

function isDomnaUser(email: string | null | undefined): boolean {
  return !!email?.endsWith("@domna.homes");
}

// GET — fetch the current linked organisation for this portfolio
export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ portfolioId: string }> },
) {
  const { portfolioId } = await params;

  const rows = await db
    .select({
      id: organisation.id,
      name: organisation.name,
      hubspotCompanyId: organisation.hubspotCompanyId,
    })
    .from(portfolioOrganisation)
    .innerJoin(organisation, eq(portfolioOrganisation.organisationId, organisation.id))
    .where(eq(portfolioOrganisation.portfolioId, BigInt(portfolioId)))
    .limit(1);

  return NextResponse.json(rows[0] ?? null);
}

// POST — connect an organisation to this portfolio (Domna only)
export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ portfolioId: string }> },
) {
  const session = await getServerSession(AuthOptions);
  if (!isDomnaUser(session?.user?.email)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const { portfolioId } = await params;
  const body = await req.json();
  const { organisationId } = body as { organisationId: string };

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

  // Upsert: delete any existing link then insert fresh
  await db
    .delete(portfolioOrganisation)
    .where(eq(portfolioOrganisation.portfolioId, BigInt(portfolioId)));

  await db.insert(portfolioOrganisation).values({
    portfolioId: BigInt(portfolioId),
    organisationId,
  });

  // Return the newly linked org
  const rows = await db
    .select({
      id: organisation.id,
      name: organisation.name,
      hubspotCompanyId: organisation.hubspotCompanyId,
    })
    .from(portfolioOrganisation)
    .innerJoin(organisation, eq(portfolioOrganisation.organisationId, organisation.id))
    .where(eq(portfolioOrganisation.portfolioId, BigInt(portfolioId)))
    .limit(1);

  return NextResponse.json(rows[0] ?? null);
}

// DELETE — disconnect the organisation from this portfolio (Domna only)
export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ portfolioId: string }> },
) {
  const session = await getServerSession(AuthOptions);
  if (!isDomnaUser(session?.user?.email)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const { portfolioId } = await params;

  await db
    .delete(portfolioOrganisation)
    .where(eq(portfolioOrganisation.portfolioId, BigInt(portfolioId)));

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