import { create } from 'zustand'

interface SprintStore {
  // sprintId → storyId[]
  sprintStoryOrder: Record<string, string[]>
  // storyId → taskId[]
  taskOrder: Record<string, string[]>

  initSprint: (sprintId: string, storyIds: string[]) => void
  addStoryToSprint: (sprintId: string, storyId: string) => void
  removeStoryFromSprint: (sprintId: string, storyId: string) => void
  reorderSprintStories: (sprintId: string, storyIds: string[]) => void
  rollbackSprint: (sprintId: string, storyIds: string[]) => void

  initTasks: (storyId: string, taskIds: string[]) => void
  reorderTasks: (storyId: string, taskIds: string[]) => void
  rollbackTasks: (storyId: string, taskIds: string[]) => void
}

export const useSprintStore = create<SprintStore>((set) => ({
  sprintStoryOrder: {},
  taskOrder: {},

  initSprint: (sprintId, storyIds) =>
    set((s) => ({ sprintStoryOrder: { ...s.sprintStoryOrder, [sprintId]: storyIds } })),

  addStoryToSprint: (sprintId, storyId) =>
    set((s) => ({
      sprintStoryOrder: {
        ...s.sprintStoryOrder,
        [sprintId]: [...(s.sprintStoryOrder[sprintId] ?? []), storyId],
      },
    })),

  removeStoryFromSprint: (sprintId, storyId) =>
    set((s) => ({
      sprintStoryOrder: {
        ...s.sprintStoryOrder,
        [sprintId]: (s.sprintStoryOrder[sprintId] ?? []).filter((id) => id !== storyId),
      },
    })),

  reorderSprintStories: (sprintId, storyIds) =>
    set((s) => ({ sprintStoryOrder: { ...s.sprintStoryOrder, [sprintId]: storyIds } })),

  rollbackSprint: (sprintId, storyIds) =>
    set((s) => ({ sprintStoryOrder: { ...s.sprintStoryOrder, [sprintId]: storyIds } })),

  initTasks: (storyId, taskIds) =>
    set((s) => ({ taskOrder: { ...s.taskOrder, [storyId]: taskIds } })),

  reorderTasks: (storyId, taskIds) =>
    set((s) => ({ taskOrder: { ...s.taskOrder, [storyId]: taskIds } })),

  rollbackTasks: (storyId, taskIds) =>
    set((s) => ({ taskOrder: { ...s.taskOrder, [storyId]: taskIds } })),
}))
