import { writable } from 'svelte/store';
import type { TeamMember } from '$lib/services/teamMemberService';
import { teamMemberService } from '$lib/services/teamMemberService';

interface CachedTeamMembers {
  data: TeamMember[];
  timestamp: number;
}

const CACHE_TTL = 5 * 60 * 1000;

function createTeamMembersStore() {
  const { subscribe, set } = writable<TeamMember[]>([]);
  let cache: CachedTeamMembers | null = null;

  return {
    subscribe,
    async load() {
      if (cache && Date.now() - cache.timestamp < CACHE_TTL) {
        return cache.data;
      }

      const data = await teamMemberService.getAll();
      cache = { data, timestamp: Date.now() };
      set(data);
      return data;
    },
    invalidate() {
      cache = null;
    }
  };
}

export const teamMembersStore = createTeamMembersStore();
