import { reactive } from "vue";
import { CurrentTeacherId } from "~/utils";

interface TeacherState {
  currentTeacherId?: string;
}

const store = reactive<TeacherState>({
  currentTeacherId: window.localStorage.getItem(CurrentTeacherId) || undefined,
});

export default function useTeacher() {
  const switchTeacher = (teacherId: string) => {
    window.localStorage.setItem(CurrentTeacherId, teacherId);
    store.currentTeacherId = teacherId;
  };

  const clearTeacher = () => {
    window.localStorage.removeItem(CurrentTeacherId);
    store.currentTeacherId = undefined;
  };

  const tryAutoSelect = (teachers: { hty_id?: string }[]) => {
    if (!store.currentTeacherId && teachers.length > 0 && teachers[0].hty_id) {
      switchTeacher(teachers[0].hty_id);
      return true;
    }
    return false;
  };

  return {
    store,
    switchTeacher,
    clearTeacher,
    tryAutoSelect,
  };
}
