/**
 * Converts a filter object (including date range keys) to Frappe filter array format.
 * Used by list pages and services for /api/resource and frappe.client.get_list.
 *
 * Date range keys (optional):
 * - creation_from -> ['creation', '>=', value]
 * - creation_to   -> ['creation', '<=', value]
 * - modified_from -> ['modified', '>=', value]
 * - modified_to   -> ['modified', '<=', value]
 *
 * Other keys: [key, '=', value] or if value is [op, val] then [key, op, val].
 */
export function toFrappeFilterArray(filters: Record<string, any>): any[] {
  if (!filters || typeof filters !== 'object') return [];
  const arr: any[] = [];
  for (const [key, value] of Object.entries(filters)) {
    if (value === undefined || value === null || value === '') continue;
    if (key === 'creation_from') {
      arr.push(['creation', '>=', value]);
    } else if (key === 'creation_to') {
      // Make end date inclusive by using creation < (end_date + 1 day)
      const d = new Date(value as string);
      if (!isNaN(d.getTime())) {
        d.setDate(d.getDate() + 1);
        const nextDay = d.toISOString().slice(0, 10);
        arr.push(['creation', '<', nextDay]);
      }
    } else if (key === 'modified_from') {
      arr.push(['modified', '>=', value]);
    } else if (key === 'modified_to') {
      // Make end date inclusive by using modified < (end_date + 1 day)
      const d = new Date(value as string);
      if (!isNaN(d.getTime())) {
        d.setDate(d.getDate() + 1);
        const nextDay = d.toISOString().slice(0, 10);
        arr.push(['modified', '<', nextDay]);
      }
    }
    else if (Array.isArray(value) && value.length >= 2) arr.push([key, value[0], value[1]]);
    else arr.push([key, '=', value]);
  }
  return arr;
}

/**
 * Build date range filter object from UI state.
 * Returns {} if no date filter is active.
 */
export function buildDateRangeFilters(
  dateFilterBy: '' | 'creation' | 'modified',
  dateStart: string,
  dateEnd: string
): Record<string, string> {
  if (!dateFilterBy || (!dateStart && !dateEnd)) return {};
  const f: Record<string, string> = {};
  if (dateFilterBy === 'creation') {
    if (dateStart) f.creation_from = dateStart;
    if (dateEnd) f.creation_to = dateEnd;
  } else {
    if (dateStart) f.modified_from = dateStart;
    if (dateEnd) f.modified_to = dateEnd;
  }
  return f;
}
