import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { LoginResponse, MeResponse } from '@arboretum/shared';
import { api } from '../lib/api';
import { wsClient } from '../lib/ws-client';

export const useAuthStore = defineStore('auth', () => {
  /** null = pas encore vérifié auprès du serveur */
  const authenticated = ref<boolean | null>(null);
  const tokenLabel = ref<string | null>(null);
  const serverVersion = ref<string | null>(null);

  async function check(): Promise<boolean> {
    try {
      const me = await api.get<MeResponse>('/api/v1/auth/me');
      tokenLabel.value = me.tokenLabel;
      serverVersion.value = me.serverVersion;
      authenticated.value = true;
    } catch {
      authenticated.value = false;
    }
    return authenticated.value === true;
  }

  async function login(token: string): Promise<void> {
    const res = await api.post<LoginResponse>('/api/v1/auth/login', { token });
    tokenLabel.value = res.label;
    authenticated.value = true;
  }

  async function logout(): Promise<void> {
    try {
      await api.post<{ ok: true }>('/api/v1/auth/logout');
    } finally {
      wsClient.disconnect();
      authenticated.value = false;
      tokenLabel.value = null;
    }
  }

  return { authenticated, tokenLabel, serverVersion, check, login, logout };
});
