import { create } from "zustand";
import { clearAuthSessionHint, markAuthSessionHint } from "@modules/auth/store/authSessionHint";

export type UserRole = "user" | "admin";
export type UserStatus = "active" | "pending" | "blocked";

export interface AuthUser {
  id: string;
  email: string;
  role: UserRole;
  is_superuser: boolean;
  status: UserStatus;
}

const TOKEN_KEY = "compton.access_token";
const USER_KEY = "compton.user";
const ENTERPRISE_KEY = "compton.enterprise_id";

function persistWespSession(accessToken: string, user: AuthUser, enterpriseId?: string | null): void {
  if (typeof window === "undefined") return;
  window.localStorage.setItem(TOKEN_KEY, accessToken);
  window.localStorage.setItem(USER_KEY, JSON.stringify(user));
  const resolvedEnterprise = enterpriseId ?? window.localStorage.getItem(ENTERPRISE_KEY) ?? "";
  if (resolvedEnterprise) {
    window.localStorage.setItem(ENTERPRISE_KEY, resolvedEnterprise);
  }
  const w = window as Window & { __WESP_ORCH__?: Record<string, string> };
  w.__WESP_ORCH__ = Object.assign({}, w.__WESP_ORCH__ || {}, {
    accessToken,
    enterpriseId: resolvedEnterprise,
    userEmail: user.email,
  });
}

function clearWespSession(): void {
  if (typeof window === "undefined") return;
  window.localStorage.removeItem(TOKEN_KEY);
  window.localStorage.removeItem(USER_KEY);
  window.localStorage.removeItem(ENTERPRISE_KEY);
}

interface AuthState {
  accessToken: string | null;
  user: AuthUser | null;
  bootstrapped: boolean;
  setSession: (accessToken: string, user: AuthUser, enterpriseId?: string | null) => void;
  clearSession: () => void;
  setBootstrapped: (bootstrapped: boolean) => void;
}

export const useAuthStore = create<AuthState>()((set) => ({
  accessToken: null,
  user: null,
  bootstrapped: false,
  setSession: (accessToken, user, enterpriseId) => {
    markAuthSessionHint();
    persistWespSession(accessToken, user, enterpriseId);
    set({ accessToken, user });
  },
  clearSession: () => {
    clearAuthSessionHint();
    clearWespSession();
    set({ accessToken: null, user: null });
  },
  setBootstrapped: (bootstrapped) => set({ bootstrapped })
}));

export { TOKEN_KEY, USER_KEY, ENTERPRISE_KEY };
