import { defineStore } from "pinia";
import type { PlayerFactionSnapshot } from "../../contractsPlayerFaction";

export const usePlayerFactionStore = defineStore("playerFaction", {
  state: () => ({
    playerFaction: null as PlayerFactionSnapshot | null,
    selectedOrganizationId: null as string | null,
    selectedDirectiveId: null as string | null,
  }),
  actions: {
    setPlayerFaction(snapshot: PlayerFactionSnapshot | null) {
      this.playerFaction = snapshot;
      if (snapshot == null) {
        this.selectedOrganizationId = null;
        this.selectedDirectiveId = null;
        return;
      }

      const knownOrganizationIds = new Set<string>([
        ...snapshot.fleets.map((entry) => entry.id),
        ...snapshot.taskForces.map((entry) => entry.id),
        ...snapshot.stationGroups.map((entry) => entry.id),
        ...snapshot.economicRegions.map((entry) => entry.id),
        ...snapshot.fronts.map((entry) => entry.id),
        ...snapshot.reserves.map((entry) => entry.id),
      ]);
      if (this.selectedOrganizationId && !knownOrganizationIds.has(this.selectedOrganizationId)) {
        this.selectedOrganizationId = null;
      }

      const knownDirectiveIds = new Set(snapshot.directives.map((entry) => entry.id));
      if (this.selectedDirectiveId && !knownDirectiveIds.has(this.selectedDirectiveId)) {
        this.selectedDirectiveId = null;
      }
    },
    selectOrganization(organizationId: string | null) {
      this.selectedOrganizationId = organizationId;
    },
    selectDirective(directiveId: string | null) {
      this.selectedDirectiveId = directiveId;
    },
  },
});
