import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { getLoginUser as getLoginUserApi, type TeacherUserInfo } from '@/api/teacher';
import { setCache, getCache, removeCache } from '@/utils/cache';

export type TeacherInfo = TeacherUserInfo;

/**
 * 老师 store - 管理老师身份的登录用户信息
 */
export const useTeacherStore = defineStore('teacher', () => {
    const teacherInfo = ref<TeacherInfo>(getCache('teacherInfo') || {});
    const isTeacherLoggedIn = computed(() => !!teacherInfo.value?.id);
    const schoolId = computed(() => String(teacherInfo.value?.schoolId || ''));

    /** 拉取老师身份的当前登录用户 */
    const getLoginUser = async () => {
        try {
            const res = await getLoginUserApi();
            teacherInfo.value = res.data || {};
            setCache('teacherInfo', teacherInfo.value);
            return teacherInfo.value;
        } catch (e) {
            console.error('[teacher] getLoginUser error', e);
            throw e;
        }
    };

    const updateTeacherInfo = (info: Partial<TeacherInfo>) => {
        teacherInfo.value = { ...teacherInfo.value, ...info };
        setCache('teacherInfo', teacherInfo.value);
    };

    const clear = () => {
        teacherInfo.value = {};
        removeCache('teacherInfo');
    };

    return {
        teacherInfo,
        isTeacherLoggedIn,
        schoolId,
        getLoginUser,
        updateTeacherInfo,
        clear,
    };
});
