import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { apiGet, apiPost } from "@/api/client";
import type { User, AuthStatus } from "@/types/auth";

export const useAuthStore = defineStore("auth", () => {
  const user = ref<User | null>(null);
  const loading = ref(true);
  const hasUsers = ref(true);
  const registrationOpen = ref(false);
  const oauthEnabled = ref(false);
  const localAuthEnabled = ref(true);

  const isAuthenticated = computed(() => user.value !== null);
  const isAdmin = computed(() => user.value?.role === "admin");

  async function checkAuth() {
    loading.value = true;
    try {
      user.value = await apiGet<User>("/api/auth/me");
    } catch {
      user.value = null;
    } finally {
      loading.value = false;
    }
  }

  async function checkHasUsers() {
    try {
      const data = await apiGet<AuthStatus>("/api/auth/status");
      hasUsers.value = data.has_users;
      registrationOpen.value = data.registration_open;
      oauthEnabled.value = data.oauth_enabled ?? false;
      localAuthEnabled.value = data.local_auth_enabled ?? true;
    } catch {
      hasUsers.value = true;
      registrationOpen.value = false;
      oauthEnabled.value = false;
      localAuthEnabled.value = true;
    }
  }

  async function login(username: string, password: string) {
    user.value = await apiPost<User>("/api/auth/login", { username, password });
  }

  async function register(username: string, password: string, email?: string) {
    user.value = await apiPost<User>("/api/auth/register", {
      username,
      password,
      email: email || undefined,
    });
  }

  async function logout() {
    await apiPost("/api/auth/logout", {});
    user.value = null;
  }

  return {
    user,
    loading,
    hasUsers,
    registrationOpen,
    oauthEnabled,
    localAuthEnabled,
    isAuthenticated,
    isAdmin,
    checkAuth,
    checkHasUsers,
    login,
    register,
    logout,
  };
});
