// Library state: the saved transcripts list + search, backed by the local
// StorageRepo (Dexie on web, expo-sqlite on native). UI/session state only —
// the record of truth lives in the repo.
import { create } from 'zustand';

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

interface TranscriptsState {
  items: TranscriptMeta[];
  loading: boolean;
  query: string;
  refresh: () => Promise<void>;
  setQuery: (q: string) => Promise<void>;
  remove: (id: string) => Promise<void>;
  rename: (id: string, title: string) => Promise<void>;
}

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

  refresh: async () => {
    set({ loading: true });
    try {
      const repo = getRepo();
      const q = get().query.trim();
      const items = q ? await repo.search(q) : await repo.list();
      set({ items });
    } finally {
      set({ loading: false });
    }
  },

  setQuery: async (q) => {
    set({ query: q });
    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();
  },
}));
