import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '../api';

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '');
  const user = ref<{ id?: string; username?: string; locale?: string } | null>(
    JSON.parse(localStorage.getItem('user') || 'null'),
  );

  async function login(username: string, password: string) {
    const { data } = await api.post('/player/auth/login', { username, password });
    token.value = data.data.token;
    user.value = data.data.user;
    localStorage.setItem('token', token.value);
    localStorage.setItem('user', JSON.stringify(user.value));
  }

  function logout() {
    token.value = '';
    user.value = null;
    localStorage.removeItem('token');
    localStorage.removeItem('user');
  }

  return { token, user, login, logout };
});
