import type { NextFunction, Request, Response } from "express";
import type { CustomField } from "@prisma/client";
import { resolveBoardAccess } from "./authz";
import { prisma } from "./prisma";

function idList(json: unknown): string[] | null {
  if (!Array.isArray(json)) return null;
  const ids = json.filter((x): x is string => typeof x === "string");
  return ids.length > 0 ? ids : null;
}

async function isBoardAdminOf(userId: string, boardId: string): Promise<boolean> {
  const board = await prisma.board.findUnique({ where: { id: boardId } });
  if (!board) return false;
  return (await resolveBoardAccess(userId, board)) === "ADMIN";
}

/** No restriction list = everyone with board access; otherwise only the listed
 * userIds (plus board admins, who can always manage every field). */
export async function canViewCustomField(
  userId: string,
  boardId: string,
  field: Pick<CustomField, "viewUserIds">
): Promise<boolean> {
  const allowed = idList(field.viewUserIds);
  if (!allowed) return true;
  if (allowed.includes(userId)) return true;
  return isBoardAdminOf(userId, boardId);
}

export async function canEditCustomField(
  userId: string,
  boardId: string,
  field: Pick<CustomField, "editUserIds">
): Promise<boolean> {
  const allowed = idList(field.editUserIds);
  if (!allowed) return true;
  if (allowed.includes(userId)) return true;
  return isBoardAdminOf(userId, boardId);
}

type MaskableCard = {
  boardId?: string;
  customFieldValues?: Array<{
    customFieldId: string;
    value: unknown;
    restricted?: boolean;
    customField?: (Pick<CustomField, "viewUserIds"> & { boardId?: string }) | null;
  }>;
};

async function maskOneCard(userId: string, card: unknown): Promise<void> {
  if (!card || typeof card !== "object") return;
  const c = card as MaskableCard;
  if (!c.boardId || !Array.isArray(c.customFieldValues)) return;

  for (const cfv of c.customFieldValues) {
    if (!cfv.customField) continue;
    // A linked card can carry values for the other board's fields too, so check
    // against the field's own board, not the card's home board.
    if (!(await canViewCustomField(userId, cfv.customField.boardId ?? c.boardId, cfv.customField))) {
      cfv.value = null;
      cfv.restricted = true;
    }
  }
}

/** Redacts any custom field value the current user isn't allowed to see, on
 * whatever shape of JSON body a route sends back — a single `{ card }`, or a
 * `{ board }` whose lists carry cards. Mounted once per router (right after
 * requireAuth) instead of touching every individual response site. */
export function maskCustomFieldsMiddleware(req: Request, res: Response, next: NextFunction) {
  const userId = req.userId;
  if (!userId) {
    next();
    return;
  }

  const originalJson = res.json.bind(res);
  res.json = ((body: unknown) => {
    void (async () => {
      try {
        if (body && typeof body === "object") {
          const b = body as { card?: unknown; board?: { lists?: Array<{ cards?: unknown[] }> } };
          if (b.card) await maskOneCard(userId, b.card);
          if (b.board?.lists) {
            for (const list of b.board.lists) {
              for (const card of list.cards ?? []) await maskOneCard(userId, card);
            }
          }
        }
      } catch {
        // Never let a masking failure block the response.
      }
      originalJson(body as never);
    })();
    return res;
  }) as typeof res.json;

  next();
}
