/**
 * Base en memoria para los specs de lecturas (OP y CxP): evalúa el `where` de Prisma sobre filas planas
 * (AND/OR/NOT, `some`, `in`, `notIn`, `not`, rangos, `contains`, con la semántica de NULL de SQL). Así los tests
 * prueban qué filas salen, no la forma del objeto `where`.
 */

export type Fila = Record<string, any>;

const OPS = ['in', 'notIn', 'not', 'gte', 'lte', 'gt', 'lt', 'equals', 'contains', 'mode'];

export const valor = (v: any) =>
  v instanceof Date ? v.getTime() : typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(v) ? Date.parse(v) : Number(v);

const compara = (op: string, v: any, x: any): boolean => {
  if (op === 'mode') return true;
  if (op === 'not')
    return x === null ? v != null : v != null && (typeof x === 'object' ? !compara('equals', v, x) : v !== x);
  if (v == null) return false;
  if (op === 'in') return x.includes(v);
  if (op === 'notIn') return !x.includes(v);
  if (op === 'equals') return v === x;
  if (op === 'contains') return String(v).toLowerCase().includes(String(x).toLowerCase());
  const a = valor(v);
  const b = valor(x);
  return op === 'gte' ? a >= b : op === 'lte' ? a <= b : op === 'gt' ? a > b : a < b;
};

export const cumple = (fila: Fila | null | undefined, where: Fila = {}): boolean =>
  Object.entries(where).every(([k, c]) => {
    if (c === undefined) return true;
    if (k === 'AND') return ([] as Fila[]).concat(c).every((w) => cumple(fila, w));
    if (k === 'OR') return (c as Fila[]).some((w) => cumple(fila, w));
    if (k === 'NOT') return !([] as Fila[]).concat(c).some((w) => cumple(fila, w));
    const v = fila?.[k];
    if (c === null) return v == null;
    if (c instanceof Date) return v != null && valor(v) === c.getTime();
    if (typeof c === 'object' && !Array.isArray(c)) {
      if ('some' in c) return ((v as Fila[]) ?? []).some((x) => cumple(x, c.some));
      if (Object.keys(c).some((op) => OPS.includes(op))) return Object.entries(c).every(([op, x]) => compara(op, v, x));
      return v != null && cumple(v, c);
    }
    return v === c;
  });
