import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { apiRequest, readSession, writeSession } from "@/lib/api";

export const useAuthStore = defineStore("auth", () => {
  const session = ref(readSession());
  const loading = ref(false);

  const isAuthenticated = computed(() => Boolean(session.value?.access_token));
  const email = computed(() => session.value?.email || "");

  function setSession(value) {
    session.value = value;
    writeSession(value);
  }

  async function login(credentials) {
    loading.value = true;
    try {
      const result = await apiRequest("/auth/login", {
        method: "POST",
        auth: false,
        body: credentials,
      });
      setSession(result);
      return result;
    } finally {
      loading.value = false;
    }
  }

  async function register(credentials) {
    loading.value = true;
    try {
      const result = await apiRequest("/auth/register", {
        method: "POST",
        auth: false,
        body: credentials,
      });
      setSession({ role: "user", status: "active", ...result });
      return result;
    } finally {
      loading.value = false;
    }
  }

  async function logout() {
    try {
      if (session.value?.access_token) {
        await apiRequest("/auth/logout", { method: "POST" });
      }
    } catch {
      // Local logout must still succeed when Redis is unavailable.
    } finally {
      setSession(null);
    }
  }

  function syncSession() {
    session.value = readSession();
  }

  return {
    session,
    loading,
    isAuthenticated,
    email,
    login,
    register,
    logout,
    syncSession,
  };
});
