import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { and, 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");
}

function linkedOrgsQuery(portfolioId: string) {
  return 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)));
}

// GET — fetch all linked organisations for this portfolio
export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ portfolioId: string }> },
) {
  const { portfolioId } = await params;
  const rows = await linkedOrgsQuery(portfolioId);
  return NextResponse.json(rows);
}

// POST — add an organisation link (Domna only, rejects duplicates)
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 });
  }

  // Reject if this org is already linked to this portfolio
  const existing = await db
    .select({ id: portfolioOrganisation.id })
    .from(portfolioOrganisation)
    .where(
      and(
        eq(portfolioOrganisation.portfolioId, BigInt(portfolioId)),
        eq(portfolioOrganisation.organisationId, organisationId),
      ),
    )
    .limit(1);

  if (existing.length > 0) {
    return NextResponse.json({ error: "Organisation already linked" }, { status: 409 });
  }

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

  const rows = await linkedOrgsQuery(portfolioId);
  return NextResponse.json(rows);
}

// DELETE — remove a specific organisation link (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;
  const body = await req.json().catch(() => ({}));
  const { organisationId } = body as { organisationId?: string };

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

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

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