import {defineStore} from 'pinia';
import {set, get} from 'idb-keyval';

export const useNews = defineStore('news', {
  state: () => ({
    articles: [] as {
      id: string,
      published: number,
      title: string,
      source: string,
      summary_de: string,
      summary_en: string
    }[], lastSync: 0, offline: false
  }),
  actions: {
    async loadLastSync() {
      const {ts} = await fetch('/meta/last-sync').then(r => r.json());
      this.lastSync = ts * 1000; // store ms
    },
    canManualSync() {
      return Date.now() - this.lastSync > 30 * 60 * 1000; // 30‑min guard
    },
    async sync(filters: Record<string, string>) {
      try {
        if (!this.canManualSync()) throw new Error('Too soon');
        const q = new URLSearchParams(filters).toString();
        const res = await fetch(`/news?${q}`);
        if (!res.ok) throw new Error('network');
        const data = await res.json();
        this.articles = data;
        this.lastSync = Date.now();
        await set(JSON.stringify(filters), data);
        this.offline = false;
      } catch (e) {
        const cached = await get(JSON.stringify(filters));
        if (cached) {
          this.articles = cached;
          this.offline = true;
        }
      }
    }
  }
});
