import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { http } from '../api/http';
import type { AdminUser } from '../api/types';

const TOKEN_KEY = 'yaoai.admin.token';
const USER_KEY = 'yaoai.admin.user';

export const useAuthStore = defineStore('auth', () => {
  const token = ref(sessionStorage.getItem(TOKEN_KEY) || '');
  const user = ref<AdminUser | null>(JSON.parse(sessionStorage.getItem(USER_KEY) || 'null'));

  const role = computed(() => user.value?.role || 'READONLY');
  const isLoggedIn = computed(() => Boolean(token.value));

  async function login(username: string, password: string) {
    const result = await http.post<string>('/auth/login', { username, password });
    token.value = result;
    sessionStorage.setItem(TOKEN_KEY, token.value);
    await fetchMe();
  }

  async function fetchMe() {
    const me = await http.get<AdminUser>('/auth/me');
    user.value = me;
    sessionStorage.setItem(USER_KEY, JSON.stringify(user.value));
  }

  async function logout() {
    try {
      await http.post('/auth/logout');
    } finally {
      logoutLocal();
    }
  }

  function logoutLocal() {
    token.value = '';
    user.value = null;
    sessionStorage.removeItem(TOKEN_KEY);
    sessionStorage.removeItem(USER_KEY);
  }

  function hasRole(allowed?: string[]) {
    return !allowed || allowed.length === 0 || allowed.includes(role.value);
  }

  return { token, user, role, isLoggedIn, login, fetchMe, logout, logoutLocal, hasRole };
});
