import {defineStore} from 'pinia';

export const useFeeds = defineStore('feeds', {
  state: () => ({list: [] as { country: string, url: string }[]}),
  actions: {
    async fetch() {
      this.list = await fetch('/feeds').then(r => r.json());
    },
    async add(country: string, url: string) {
      await fetch('/feeds', {
        method: 'POST', headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({country, url})
      });
      await this.fetch();
    },
    async remove(url: string) {
      await fetch(`/feeds?url=${encodeURIComponent(url)}`, {method: 'DELETE'});
      await this.fetch();
    },
    async loadFeeds() {
      try {
        const response = await fetch('/feeds');
        if (response.ok) {
          const data = await response.json();
          this.list = data;
        }
      } catch (error) {
        console.error('Failed to load feeds:', error);
      }
    }
  }
});
