/**
 * Prisma en memoria para `autorizaciones_descuento`, solo para specs: evalúa
 * el subconjunto de `where` que usan los servicios (igualdad, null, `in`,
 * `gt`, `OR`) y ordena por `created_at`. Así los tests prueban el resultado
 * con datos, no la forma de la consulta.
 */
export type AutorizacionFalsa = {
  id: string;
  empresa_id: string;
  cliente_id: string;
  factura_cab_id: string | null;
  factura_cuota_id?: string | null;
  tipo: string;
  estado: string;
  expires_at: Date | null;
  created_at: Date;
  descuento_porcentaje?: number | null;
  descuento_monto?: number | null;
  motivo?: string | null;
};

export function cumpleWhere(fila: any, where: any): boolean {
  if (!where) return true;
  return Object.entries(where).every(([k, cond]: [string, any]) => {
    if (k === 'OR') return (cond as any[]).some((w) => cumpleWhere(fila, w));
    if (k === 'AND') return (cond as any[]).every((w) => cumpleWhere(fila, w));
    const v = fila[k] ?? null;
    if (cond === null) return v === null;
    if (cond instanceof Date) return v instanceof Date && +v === +cond;
    if (typeof cond === 'object') {
      if ('in' in cond && !cond.in.includes(v)) return false;
      if ('gt' in cond && !(v !== null && v > cond.gt)) return false;
      return true;
    }
    return v === cond;
  });
}

export function prismaAutorizacionesFalso(filas: AutorizacionFalsa[], facturas: Record<string, string> = {}) {
  const buscar = ({ where, orderBy }: any) => {
    const r = filas.filter((f) => cumpleWhere(f, where));
    if (orderBy?.created_at === 'desc') r.sort((a, b) => +b.created_at - +a.created_at);
    return r;
  };
  return {
    autorizaciones_descuento: {
      findFirst: jest.fn(async (args: any) => buscar(args)[0] ?? null),
      findMany: jest.fn(async (args: any) => buscar(args)),
    },
    factura_cab: {
      findFirst: jest.fn(async ({ where }: any) =>
        facturas[where.id] ? { cliente_id: facturas[where.id] } : null,
      ),
    },
  };
}
