import { create } from 'zustand';
import * as authApi from '@/lib/api/auth';
import { getQueryClient } from '@/lib/query/query-client';
import { resetAnalytics } from '@/lib/analytics';
import { logout as kratosLogout, whoami } from '@/lib/kratos';
import type { UserResponse } from '@/lib/api/auth';

// ---------------------------------------------------------------------------
// Auth store
// ---------------------------------------------------------------------------
// Identity is owned by Ory Kratos. Login / registration / recovery now happen
// on dedicated Kratos self-service flow pages, NOT through this store. What
// this store keeps is:
//   - the current Kratos session state (authenticated yes/no)
//   - the honeyDue-side user profile (from GET /auth/me)
//   - a logout action that drives the Kratos browser logout flow
// ---------------------------------------------------------------------------

interface AuthState {
  /** honeyDue-side user profile (GET /auth/me), null if not loaded / signed out. */
  user: UserResponse | null;
  /** True once a live Kratos session has been confirmed. */
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;

  /**
   * Confirm the Kratos session and, if valid, load the honeyDue profile.
   * Call this on app startup to hydrate the store.
   */
  hydrate: () => Promise<void>;
  /** Reload just the honeyDue profile (after a profile update). */
  fetchUser: () => Promise<void>;
  /** Drive the Kratos browser logout flow and clear local state. */
  logout: () => Promise<void>;
  clearError: () => void;
}

export const useAuthStore = create<AuthState>()((set) => ({
  user: null,
  isAuthenticated: false,
  isLoading: false,
  error: null,

  hydrate: async () => {
    set({ isLoading: true, error: null });
    try {
      const session = await whoami();
      if (!session || !session.active) {
        set({ user: null, isAuthenticated: false, isLoading: false });
        return;
      }
      // Session is valid — load the honeyDue-side profile.
      try {
        const user = await authApi.getCurrentUser();
        set({ user, isAuthenticated: true, isLoading: false });
      } catch {
        // Session exists but the honeyDue profile call failed; still treat
        // the user as authenticated so the app can render.
        set({ user: null, isAuthenticated: true, isLoading: false });
      }
    } catch {
      set({ user: null, isAuthenticated: false, isLoading: false });
    }
  },

  fetchUser: async () => {
    try {
      const user = await authApi.getCurrentUser();
      set({ user, isAuthenticated: true });
    } catch {
      // Leave existing state; hydrate() owns auth-state transitions.
    }
  },

  logout: async () => {
    set({ isLoading: true, error: null });
    // Clear local app state before handing off to Kratos.
    getQueryClient().clear();
    resetAnalytics();
    set({ user: null, isAuthenticated: false, isLoading: false, error: null });
    // Drives the Kratos browser logout flow, which clears the session cookie
    // and redirects the browser.
    await kratosLogout();
  },

  clearError: () => set({ error: null }),
}));
