import AsyncStorage from '@react-native-async-storage/async-storage';

const BASE = process.env.EXPO_PUBLIC_API_BASE ?? 'https://konferencjapodatkowa.pl';
const CACHE_KEY = 'conferences:v1';
const FIELDS =
  'title,field_data,field_miejsce,field_rodzaj,field_sposob_udzia,field_strona_konferencji,field_organizator';

export type Conference = {
  id: string;
  title: string;
  start: string;
  end: string | null;
  place: string | null;
  organizer: string | null;
  url: string | null;
};

type Item = { id: string; attributes: Record<string, any> };

function map(i: Item): Conference {
  const a = i.attributes;
  return {
    id: i.id,
    title: a.title,
    start: a.field_data?.value,
    end: a.field_data?.end_value ?? null,
    place: a.field_miejsce ?? null,
    organizer: a.field_organizator ?? null,
    url: a.field_strona_konferencji?.uri ?? null,
  };
}

// Follows links.next (the server caps pages; 20 per page keeps payloads small).
export async function loadConferences(): Promise<{ items: Conference[]; offline: boolean }> {
  try {
    let url: string | undefined =
      `${BASE}/jsonapi/node/conference?fields[node--conference]=${FIELDS}` +
      `&sort=-field_data.value&page[limit]=20`;
    const items: Conference[] = [];
    while (url) {
      const res: Response = await fetch(url, { headers: { Accept: 'application/vnd.api+json' } });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json: { data: Item[]; links?: { next?: { href: string } } } = await res.json();
      items.push(...json.data.map(map));
      url = json.links?.next?.href;
    }
    await AsyncStorage.setItem(CACHE_KEY, JSON.stringify(items));
    return { items, offline: false };
  } catch {
    const cached = await AsyncStorage.getItem(CACHE_KEY);
    return { items: cached ? JSON.parse(cached) : [], offline: true };
  }
}
