/**
 * Shared utilities for transforming data between backend (snake_case) and frontend (camelCase) formats.
 */

// Fields that should remain as strings even if they look numeric
const STRING_FIELDS = new Set([
  'sku', 'title', 'brand', 'vendor', 'barcode',
  'vendor_reference', 'notions_reference', 'harmonized_tariff_code'
]);

/**
 * Converts a snake_case key to camelCase.
 * Handles numeric suffixes like sales_7d -> sales7d
 */
export function snakeToCamelCase(key: string): string {
  let result = key;
  // First handle cases like sales_7d -> sales7d
  result = result.replace(/_(\d+[a-z])/g, '$1');
  // Then handle regular snake_case -> camelCase
  result = result.replace(/_([a-z])/g, (_, p1) => p1.toUpperCase());
  return result;
}

/**
 * Transforms a single metrics row from snake_case DB format to camelCase frontend format.
 * Converts numeric strings to actual numbers except for known string fields and dates.
 */
export function transformMetricsRow(row: Record<string, any>): Record<string, any> {
  const transformed: Record<string, any> = {};

  for (const [key, value] of Object.entries(row)) {
    const camelKey = snakeToCamelCase(key);

    if (
      typeof value === 'string' &&
      value !== '' &&
      !isNaN(Number(value)) &&
      !key.toLowerCase().includes('date') &&
      !STRING_FIELDS.has(key)
    ) {
      transformed[camelKey] = Number(value);
    } else {
      transformed[camelKey] = value;
    }
  }

  // Ensure pid is a number
  if (transformed.pid !== undefined) {
    transformed.pid = typeof transformed.pid === 'string'
      ? parseInt(transformed.pid, 10)
      : transformed.pid;
  }

  return transformed;
}

/**
 * Maps frontend operator names to backend query param suffixes.
 */
export const OPERATOR_MAP: Record<string, string> = {
  '=': 'eq', '!=': 'ne', '>': 'gt', '>=': 'gte', '<': 'lt', '<=': 'lte',
  'between': 'between', 'in': 'in', 'not_in': 'ne',
  'contains': 'ilike', 'equals': 'eq',
  'starts_with': 'starts_with', 'ends_with': 'ends_with', 'not_contains': 'not_contains',
  'is_empty': 'is_empty', 'is_not_empty': 'is_not_empty',
  'is_true': 'is_true', 'is_false': 'is_false',
};
