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 newsTableQueryOptions = {
  sortableFields: [
    "title",
    "category",
    "isFeatured",
    "isActive",
    "viewCount",
    "createdAt",
  ],
  filters: {
    title: {
      field: "title",
      transform: toContainsRegex,
    },
    category: {
      field: "category",
      transform: (value) => String(value).trim().toLowerCase(),
    },
    isFeatured: {
      field: "isFeatured",
      type: "boolean",
      allowedValues: ["true", "false"],
    },
    isActive: {
      field: "isActive",
      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 buildNewsTableQuery = (rawQuery) =>
  buildTableQuery(rawQuery, newsTableQueryOptions);

export const buildPublicNewsQuery = (rawQuery = {}) => {
  const query = {};
  const { category, isActive, isFeatured, search } = rawQuery;

  if (category) query.category = String(category).trim().toLowerCase();
  if (isActive !== undefined) query.isActive = isActive === "true";
  if (isFeatured !== undefined) query.isFeatured = isFeatured === "true";

  if (search) {
    const term = toContainsRegex(String(search).trim());
    query.$or = [
      { title: term },
      { excerpt: term },
      { content: term },
      { tags: term },
    ];
  }

  return query;
};
