import { db } from "@/app/db/db";
import { portfolioUsers } from "@/app/db/schema/portfolio";
import { and, eq } from "drizzle-orm";
import { NextResponse } from "next/server";
import type { Session } from "next-auth";
import {
  canAdminister,
  isDomnaEmail,
  type PortfolioPrivilege,
} from "./portfolioAdmin";

// Resolves the effective privilege a session has on a given portfolio.
// Highest-wins: an explicit "creator" or "admin" membership ranks above the
// implicit "domna" employee privilege; otherwise Domna employees get admin
// powers without being a member; otherwise the membership role is returned.
export async function resolvePortfolioPrivilege({
  portfolioId,
  userId,
  userEmail,
}: {
  portfolioId: bigint;
  userId: bigint;
  userEmail: string;
}): Promise<PortfolioPrivilege> {
  const [membership] = await db
    .select({ role: portfolioUsers.role })
    .from(portfolioUsers)
    .where(
      and(
        eq(portfolioUsers.portfolioId, portfolioId),
        eq(portfolioUsers.userId, userId),
      ),
    )
    .limit(1);

  if (membership?.role === "creator") return "creator";
  if (membership?.role === "admin") return "admin";
  if (isDomnaEmail(userEmail)) return "domna";
  if (membership?.role === "write") return "write";
  if (membership?.role === "read") return "read";
  return "none";
}

// Convenience: returns an HTTP response if the session can't administer the
// portfolio, otherwise null. Use at the top of mutating route handlers:
//
//   const denied = await denyIfNotAdmin(portfolioId, session);
//   if (denied) return denied;
export async function denyIfNotAdmin(
  portfolioId: bigint,
  session: Session | null,
): Promise<NextResponse | null> {
  if (!session?.user?.dbId || !session.user.email) {
    return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
  }
  const privilege = await resolvePortfolioPrivilege({
    portfolioId,
    userId: BigInt(session.user.dbId),
    userEmail: session.user.email,
  });
  if (!canAdminister(privilege)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }
  return null;
}
