import { buildTableQuery } from "$helpers/table-query/table-query.helper.js";

const escapeRegex = (value = "") =>
  String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

const toContainsRegex = (value) => new RegExp(escapeRegex(value), "i");

const transactionTableQueryOptions = {
  sortableFields: [
    "fundKey",
    "amountRial",
    "status",
    "gateway",
    "cardMask",
    "createdAt",
  ],
  filters: {
    fundKey: {
      field: "fundKey",
      transform: toContainsRegex,
    },
    status: {
      field: "status",
      allowedValues: [
        "initiated",
        "token_received",
        "paid",
        "failed",
        "cancelled",
      ],
    },
    gateway: {
      field: "gateway",
      allowedValues: ["parsian", "payment_card"],
    },
    amountMin: {
      field: "amountRial",
      type: "number",
      operator: "gte",
    },
    amountMax: {
      field: "amountRial",
      type: "number",
      operator: "lte",
    },
    createdFrom: {
      field: "createdAt",
      type: "date",
      operator: "gte",
    },
    createdTo: {
      field: "createdAt",
      type: "date",
      operator: "lte",
      endOfDay: true,
    },
  },
  defaultSort: { field: "createdAt", direction: "desc" },
};

export const buildTransactionTableQuery = (rawQuery) =>
  buildTableQuery(rawQuery, transactionTableQueryOptions);
