import { defineStore } from "pinia";
import type { ShipSnapshot } from "../../contractsShips";
import type { StationSnapshot } from "../../contractsInfrastructure";
import type { FactionSnapshot } from "../../contractsFactions";
import type { MarketOrderSnapshot } from "../../contractsEconomy";
import type { GeopoliticalStateSnapshot } from "../../contractsGeopolitics";
import type { SystemSnapshot } from "../../contractsCelestial";

export const useGmStore = defineStore("gm", {
  state: () => ({
    systems: [] as SystemSnapshot[],
    ships: [] as ShipSnapshot[],
    stations: [] as StationSnapshot[],
    factions: [] as FactionSnapshot[],
    marketOrders: [] as MarketOrderSnapshot[],
    geopolitics: null as GeopoliticalStateSnapshot | null,
  }),
  actions: {
    updateWorld(
      systems: SystemSnapshot[],
      ships: ShipSnapshot[],
      stations: StationSnapshot[],
      factions: FactionSnapshot[],
      marketOrders: MarketOrderSnapshot[],
      geopolitics: GeopoliticalStateSnapshot | null,
    ) {
      this.systems = systems;
      this.ships = ships;
      this.stations = stations;
      this.factions = factions;
      this.marketOrders = marketOrders;
      this.geopolitics = geopolitics;
    },
    upsertShip(ship: ShipSnapshot) {
      const index = this.ships.findIndex((candidate) => candidate.id === ship.id);
      if (index >= 0) {
        this.ships.splice(index, 1, ship);
        return;
      }
      this.ships.push(ship);
    },
    upsertFaction(faction: FactionSnapshot) {
      const index = this.factions.findIndex((candidate) => candidate.id === faction.id);
      if (index >= 0) {
        this.factions.splice(index, 1, faction);
        return;
      }
      this.factions.push(faction);
    },
    upsertStation(station: StationSnapshot) {
      const index = this.stations.findIndex((candidate) => candidate.id === station.id);
      if (index >= 0) {
        this.stations.splice(index, 1, station);
        return;
      }
      this.stations.push(station);
    },
  },
});
