import { computed, reactive } from 'vue';
import { api } from '@/lib/api';

const state = reactive({
  initialized: false,
  loading: false,
  error: '',
  publicData: { organization: {}, notices: [], exams: [], stats: {} },
  user: null,
  profile: null,
  permissions: [],
  scopeLabel: ''
});

let bootstrapPromise;

async function loadPublic() {
  state.publicData = await api('/api/public/home');
  return state.publicData;
}

async function refreshSession() {
  try {
    const session = await api('/api/auth/me');
    state.user = session.user || null;
    state.profile = session.profile || null;
    state.permissions = session.permissions || [];
    state.scopeLabel = session.scopeLabel || '';
    return session;
  } catch (error) {
    if (error.status !== 401) throw error;
    clearSession();
    return { user: null, profile: null, permissions: [] };
  }
}

async function bootstrap({ refresh = false } = {}) {
  if (state.initialized && !refresh) return state;
  if (bootstrapPromise && !refresh) return bootstrapPromise;
  state.loading = true;
  state.error = '';
  bootstrapPromise = Promise.all([loadPublic(), refreshSession()])
    .then(() => {
      state.initialized = true;
      return state;
    })
    .catch(error => {
      state.error = error.message || '系统基础信息加载失败';
      throw error;
    })
    .finally(() => {
      state.loading = false;
      bootstrapPromise = null;
    });
  return bootstrapPromise;
}

function setSession(session) {
  state.user = session.user || null;
  state.profile = session.profile || null;
  state.permissions = session.permissions || [];
  state.scopeLabel = session.scopeLabel || '';
}

function clearSession() {
  state.user = null;
  state.profile = null;
  state.permissions = [];
  state.scopeLabel = '';
}

async function logout() {
  await api('/api/auth/logout', { method: 'POST' });
  clearSession();
  await loadPublic();
}

function homeFor(user = state.user) {
  if (!user) return '/auth/login';
  if (user.role === 'candidate') {
    if (user.mustChangePassword || !state.profile?.profileCompleted) return '/candidate/onboarding';
    return '/candidate/dashboard';
  }
  if (user.role === 'admission_school') return '/admission/dashboard';
  return '/admin/dashboard';
}

export const sessionStore = {
  state,
  user: computed(() => state.user),
  profile: computed(() => state.profile),
  publicData: computed(() => state.publicData),
  isAuthenticated: computed(() => Boolean(state.user)),
  bootstrap,
  loadPublic,
  refreshSession,
  setSession,
  clearSession,
  logout,
  homeFor
};
