// Courses list state, backed by the local StorageRepo. UI/session state only.
import { create } from 'zustand';

import { getRepo, type Course, type CourseDraft } from '@/lib/db';

interface CoursesState {
  items: Course[];
  loading: boolean;
  refresh: () => Promise<void>;
  createCourse: (draft: CourseDraft) => Promise<Course>;
  rename: (id: string, name: string) => Promise<void>;
  remove: (id: string) => Promise<void>;
}

export const useCourses = create<CoursesState>((set, get) => ({
  items: [],
  loading: false,

  refresh: async () => {
    set({ loading: true });
    try {
      set({ items: await getRepo().listCourses() });
    } finally {
      set({ loading: false });
    }
  },

  createCourse: async (draft) => {
    const course = await getRepo().createCourse(draft);
    await get().refresh();
    return course;
  },

  rename: async (id, name) => {
    await getRepo().updateCourse(id, { name });
    await get().refresh();
  },

  remove: async (id) => {
    await getRepo().deleteCourse(id);
    await get().refresh();
  },
}));
