import { api } from '../../services/api';

export type SubscriberPreferences = {
  blogs?: boolean;
  matches?: boolean;
  events?: boolean;
  scores?: boolean;
  competitions?: string; // comma-separated list for now
  categories?: string; // legacy key used by backend filtering
  // allow future keys without strict typing issues
  [key: string]: boolean | string | number | null | string[] | undefined;
};

type NormalizedPreferences = Record<string, boolean | string | number | null>;

const normalizePreferences = (preferences: SubscriberPreferences = {}): NormalizedPreferences => {
  const normalized: NormalizedPreferences = {};

  Object.entries(preferences).forEach(([key, raw]) => {
    if (raw === undefined) {
      return;
    }

    if (typeof raw === 'boolean' || typeof raw === 'number') {
      normalized[key] = raw;
      return;
    }

    if (typeof raw === 'string') {
      normalized[key] = raw.trim();
      return;
    }

    if (Array.isArray(raw)) {
      const joined = (raw as Array<unknown>)
        .map((item: unknown) => {
          if (typeof item === 'string') {
            return item.trim();
          }
          if (item === null || item === undefined) {
            return '';
          }
          return String(item);
        })
        .filter((item: string) => item !== '');
      normalized[key] = joined.join(', ');
      return;
    }

    if (raw === null) {
      normalized[key] = null;
      return;
    }

    try {
      normalized[key] = JSON.stringify(raw);
    } catch {
      normalized[key] = String(raw);
    }
  });

  const competitions = normalized['competitions'];
  if (typeof competitions === 'string' && !normalized['categories']) {
    normalized['categories'] = competitions;
  }

  return normalized;
};

export type PreferencesResponse = {
  email: string;
  is_active: boolean;
  preferences: SubscriberPreferences;
};

export async function getPreferences(token: string): Promise<PreferencesResponse> {
  const { data } = await api.get<PreferencesResponse>(`/newsletter/preferences`, {
    params: { token },
  });
  return data;
}

export async function savePreferences(token: string, preferences: SubscriberPreferences): Promise<{ message: string }> {
  const normalized = normalizePreferences(preferences);
  if (typeof normalized.competitions === 'string' && !normalized.categories) {
    normalized.categories = normalized.competitions;
  }
  const { data } = await api.post<{ message: string }>(`/newsletter/preferences`, {
    token,
    preferences: normalized,
  });
  return data;
}

export async function unsubscribeToken(token: string): Promise<{ message: string }> {
  const { data } = await api.post<{ message: string }>(`/newsletter/unsubscribe-token`, { token });
  return data;
}
