import { defineStore } from "pinia";
import { ref } from "vue";
import { authService } from "../services/authService";

export const useAuthStore = defineStore("auth", () => {
  const user = ref(JSON.parse(localStorage.getItem("user")) || null);
  const isAuthenticated = ref(!!user.value);
  const error = ref(null);

  async function login({ username, password }) {
    error.value = null;
    try {
      const data = await authService.login(username, password);
      
      const userData = {
        username,
        token: data.access_token,
        tokenType: data.token_type
      };

      user.value = userData;
      isAuthenticated.value = true;
      localStorage.setItem("user", JSON.stringify(userData));
      
      // Fetch full profile to get roles/admin status
      await fetchCurrentUser();
      
      return true;
    } catch (err) {
      console.error('Login failed:', err);
      // Backend error format: { detail: "message" } usually
      error.value = err.response?.data?.detail || 'Login failed. Please check your credentials.';
      return false;
    }
  }

  async function register({ username, password, fullName }) {
    error.value = null;
    try {
      await authService.register(username, password, fullName);
      return true;
    } catch (err) {
      console.error('Registration failed:', err);
      error.value = err.response?.data?.detail || 'Registration failed. Please try again.';
      return false;
    }
  }

  async function fetchCurrentUser() {
    try {
      const userData = await authService.getMe();
      // Merge with existing session data if needed, or just update user object
      // We keep the token from login, but update other fields
      user.value = { ...user.value, ...userData };
      localStorage.setItem("user", JSON.stringify(user.value));
    } catch (err) {
      console.error('Failed to fetch user profile:', err);
    }
  }
  
  const isAdmin = () => user.value?.is_admin === true;

  function logout() {
    user.value = null;
    isAuthenticated.value = false;
    localStorage.removeItem("user");
  }

  return { user, isAuthenticated, error, login, register, logout, fetchCurrentUser, isAdmin };
});
