import { writable } from "svelte/store";
import type { Ligatabelle } from "../model/models";
import {configuration} from "./configuration";

export type RiegeSelection = {
  riege?: number;
  turnier?: number;
};
export const liga = writable<Ligatabelle | undefined>();

export const loadRiege = async (selection: RiegeSelection) => {
  liga.set(undefined);
  try {
    const response = await fetch(
      selection.riege
        ? `${configuration.baseUri || ''}/api/v2/ergebnisse/formationen/riegen/${selection.riege}`
        : `${configuration.baseUri || ''}/api/v2/ergebnisse/formationen/formationsturniere/${selection.turnier}`
    );

    if (!response.ok) {
      throw new Error(
        `Failed to fetch liga: ${response.status} ${response.statusText}`
      );
    }

    const data = await response.json();
    liga.set(data);
  } catch (err) {
    console.error("Error loading liga:", err);
  }
};
