export const TRACKER_TABLE_COLUMNS = [
  { key: 'due', label: 'Due' },
  { key: 'expected', label: 'Expected' },
  { key: 'previous', label: 'Last Month' },
  { key: 'paid', label: 'Paid' },
  { key: 'paid_date', label: 'Paid Date' },
  { key: 'status', label: 'Status' },
  { key: 'action', label: 'Action' },
  { key: 'notes', label: 'Notes' },
];

export const TRACKER_TABLE_COLUMN_KEYS = TRACKER_TABLE_COLUMNS.map(column => column.key);
export const DEFAULT_TRACKER_TABLE_COLUMNS = [...TRACKER_TABLE_COLUMN_KEYS];

export function parseTrackerTableColumns(value: unknown): string[] {
  if (Array.isArray(value)) return normalizeTrackerTableColumns(value);
  if (!value) return DEFAULT_TRACKER_TABLE_COLUMNS;

  try {
    const parsed = JSON.parse(value as string);
    return normalizeTrackerTableColumns(parsed);
  } catch {
    return DEFAULT_TRACKER_TABLE_COLUMNS;
  }
}

export function normalizeTrackerTableColumns(columns: unknown): string[] {
  const valid = new Set(TRACKER_TABLE_COLUMN_KEYS);
  return Array.isArray(columns)
    ? columns.filter(column => valid.has(column))
      .filter((column, index, all) => all.indexOf(column) === index)
    : DEFAULT_TRACKER_TABLE_COLUMNS;
}

export function trackerTableColumnsToSetting(columns: unknown): string {
  return JSON.stringify(normalizeTrackerTableColumns(columns));
}
