import { reactive } from "vue";
import type { AuthSession } from "./types";

const authStorageKey = "companytool.auth";

export const authState = reactive<{
  session: AuthSession | null;
}>({
  session: loadAuthSession()
});

export function setAuthSession(session: AuthSession) {
  authState.session = session;
  window.localStorage.setItem(authStorageKey, JSON.stringify(session));
}

export function updateAuthSession(partial: Partial<AuthSession>) {
  if (!authState.session) return;
  setAuthSession({ ...authState.session, ...partial });
}

export function clearAuthSession() {
  authState.session = null;
  window.localStorage.removeItem(authStorageKey);
}

function loadAuthSession(): AuthSession | null {
  try {
    const raw = window.localStorage.getItem(authStorageKey);
    if (!raw) return null;
    const session = JSON.parse(raw) as Partial<AuthSession>;
    if (!session.email || !session.userId) return null;
    if (!session.accessToken) return null;
    return {
      email: session.email,
      userId: session.userId,
      accessToken: session.accessToken,
      organizationId: session.organizationId ?? null,
      mustChangePassword: session.mustChangePassword === true
    };
  } catch {
    return null;
  }
}
