import mongoose from "mongoose";
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 toObjectId = (value) => {
  if (!mongoose.Types.ObjectId.isValid(value)) {
    const error = new Error("نقش انتخاب‌شده معتبر نیست.");
    error.status = 400;
    throw error;
  }

  return value;
};

const userTableQueryOptions = {
  sortableFields: ["fullName", "mobile", "isSejamVerified", "createdAt"],
  filters: {
    fullName: {
      field: "fullName",
      transform: toContainsRegex,
    },
    nationalId: {
      field: "nationalId",
      transform: toContainsRegex,
    },
    businessID: {
      field: "businessID",
      transform: toContainsRegex,
    },
    mobile: {
      field: "mobile",
      transform: toContainsRegex,
    },
    role: {
      field: "role",
      transform: toObjectId,
    },
    isSejamVerified: {
      field: "isSejamVerified",
      type: "boolean",
      allowedValues: ["true", "false"],
    },
    createdFrom: {
      field: "createdAt",
      type: "date",
      operator: "gte",
    },
    createdTo: {
      field: "createdAt",
      type: "date",
      operator: "lte",
      endOfDay: true,
    },
  },
  defaultSort: { field: "createdAt", direction: "desc" },
};

export const buildUserTableQuery = (rawQuery) =>
  buildTableQuery(rawQuery, userTableQueryOptions);
