import type { CustomField, Prisma } from "@prisma/client";
import { HttpError } from "../../middleware/errorHandler";
import { getAccessibleBoardIds, isSystemAdmin, requireBoardAccess } from "../authz";
import { canViewCustomField } from "../customFieldAccess";
import { prisma } from "../prisma";

// The assistant's view of the world for one user. Mirrors the API's own rules:
//  - only boards whose CONTENT the user can open (getAccessibleBoardIds: explicit
//    membership, workspace admin, org admin, system admin; VIP/PRIVATE respected),
//  - portal requesters (VIEWER + isPortalRequester, not an admin) only see the cards
//    they submitted on that board, exactly like the board page does,
//  - custom field values the user isn't allowed to see are never handed to the model.

export type AssistantScope = {
  userId: string;
  isSystemAdmin: boolean;
  boardIds: string[];
  /** Boards where the user may only see cards they submitted through the portal. */
  submitterOnlyBoardIds: Set<string>;
};

export async function loadScope(userId: string): Promise<AssistantScope> {
  const admin = await isSystemAdmin(userId);
  const boardIds = await getAccessibleBoardIds(userId);
  const submitterOnlyBoardIds = new Set<string>();
  if (!admin) {
    const portal = await prisma.boardMember.findMany({
      where: { userId, isPortalRequester: true, role: "VIEWER", boardId: { in: boardIds } },
      select: { boardId: true, board: { select: { workspaceId: true, workspaceLinks: { select: { workspaceId: true } } } } },
    });
    for (const p of portal) {
      const workspaceIds = [p.board.workspaceId, ...p.board.workspaceLinks.map((l) => l.workspaceId)];
      const wsAdmin = await prisma.workspaceMember.findFirst({ where: { userId, role: "ADMIN", workspaceId: { in: workspaceIds } } });
      if (!wsAdmin) submitterOnlyBoardIds.add(p.boardId);
    }
  }
  return { userId, isSystemAdmin: admin, boardIds, submitterOnlyBoardIds };
}

/** Prisma filter for cards this user may see (optionally narrowed to some boards). */
export function visibleCardWhere(scope: AssistantScope, boardIds?: string[]): Prisma.CardWhereInput {
  const ids = boardIds ? boardIds.filter((id) => scope.boardIds.includes(id)) : scope.boardIds;
  const open = ids.filter((id) => !scope.submitterOnlyBoardIds.has(id));
  const restricted = ids.filter((id) => scope.submitterOnlyBoardIds.has(id));
  return {
    isArchived: false,
    OR: [
      ...(open.length ? [{ boardId: { in: open } }] : []),
      ...(restricted.length ? [{ boardId: { in: restricted }, submitterId: scope.userId }] : []),
      // Nothing visible: a filter that matches no row.
      ...(open.length === 0 && restricted.length === 0 ? [{ id: "__none__" }] : []),
    ],
  };
}

export function assertBoardVisible(scope: AssistantScope, boardId: string) {
  if (!scope.boardIds.includes(boardId)) throw new HttpError(404, "Board not found or you don't have access to it (use list_boards to look up the right id)");
}

/** Board where the user can make changes (MEMBER or above), re-checked on confirm. */
export async function assertBoardWritable(scope: AssistantScope, boardId: string) {
  assertBoardVisible(scope, boardId);
  if (scope.submitterOnlyBoardIds.has(boardId)) throw new HttpError(403, "You can only view your own requests on this board");
  await requireBoardAccess(scope.userId, boardId, "MEMBER");
}

export async function loadVisibleCard<T extends Prisma.CardInclude>(scope: AssistantScope, cardId: string, include: T) {
  const card = await prisma.card.findFirst({ where: { id: cardId, ...visibleCardWhere(scope) }, include });
  if (!card) throw new HttpError(404, "Card not found or you don't have access to it");
  return card;
}

/** Per-request cache of "may this user see field X" answers. */
export function fieldVisibility(scope: AssistantScope) {
  const cache = new Map<string, boolean>();
  return async (field: CustomField) => {
    if (!cache.has(field.id)) cache.set(field.id, await canViewCustomField(scope.userId, field.boardId, field));
    return cache.get(field.id)!;
  };
}
