// Library state: the saved transcripts list + search + course filter, backed by
// the local StorageRepo. UI/session state only — the repo is the record of truth.
import { create } from 'zustand';

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

/** 'all' = every transcript · null = Unsorted · string = a specific course id. */
export type CourseFilter = 'all' | null | string;

interface TranscriptsState {
  items: TranscriptMeta[];
  loading: boolean;
  query: string;
  courseFilter: CourseFilter;
  refresh: () => Promise<void>;
  setQuery: (q: string) => Promise<void>;
  setCourseFilter: (f: CourseFilter) => Promise<void>;
  remove: (id: string) => Promise<void>;
  rename: (id: string, title: string) => Promise<void>;
  reassign: (id: string, courseId: string | null) => Promise<void>;
}

export const useTranscripts = create<TranscriptsState>((set, get) => ({
  items: [],
  loading: false,
  query: '',
  courseFilter: 'all',

  refresh: async () => {
    set({ loading: true });
    try {
      const repo = getRepo();
      const q = get().query.trim();
      const cf = get().courseFilter;
      let items: TranscriptMeta[];
      if (q) {
        // Search across everything, then narrow to the active course filter.
        items = await repo.search(q);
        if (cf !== 'all') items = items.filter((t) => (t.courseId ?? null) === cf);
      } else {
        items = cf === 'all' ? await repo.list() : await repo.listByCourse(cf);
      }
      set({ items });
    } finally {
      set({ loading: false });
    }
  },

  setQuery: async (q) => {
    set({ query: q });
    await get().refresh();
  },

  setCourseFilter: async (f) => {
    set({ courseFilter: f });
    await get().refresh();
  },

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

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

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