'use client';

// ============================================================
// Zustand Auth Store
// 大厂模式：Zustand 管理轻量客户端状态（登录会话）
// 替代旧版 React Context（auth-context.tsx）
// ============================================================

import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import type { AdminUser } from '@/domain/entities';
import { authRepository } from '@/infrastructure/repositories/auth.repository';

interface AuthState {
  // State
  user: AdminUser | null;
  token: string | null;
  refreshToken: string | null;
  isLoading: boolean;
  isAuthenticated: boolean;

  // Actions
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
  /** 内部：token refresh 成功后更新 accessToken */
  _updateToken: (accessToken: string) => void;
  /** 内部：Zustand persist 重水合后调用，同步 isAuthenticated */
  _onRehydrate: () => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      refreshToken: null,
      isLoading: true,
      isAuthenticated: false,

      login: async (email, password) => {
        const { user, tokens } = await authRepository.login(email, password);
        set({
          user,
          token: tokens.accessToken,
          refreshToken: tokens.refreshToken,
          isAuthenticated: true,
          isLoading: false,
        });
      },

      logout: () => {
        authRepository.logout();
        set({ user: null, token: null, refreshToken: null, isAuthenticated: false });
      },

      _updateToken: (accessToken: string) => {
        set({ token: accessToken });
      },

      _onRehydrate: () => {
        const { token } = get();
        set({ isAuthenticated: !!token, isLoading: false });
      },
    }),
    {
      name: 'gcx-admin-auth',
      storage: createJSONStorage(() => {
        // SSR 安全：服务端返回 no-op storage
        if (typeof window === 'undefined') {
          return {
            getItem: () => null,
            setItem: () => {},
            removeItem: () => {},
          };
        }
        return localStorage;
      }),
      partialize: (state) => ({ user: state.user, token: state.token, refreshToken: state.refreshToken }),
      onRehydrateStorage: () => (state) => {
        if (state) state._onRehydrate();
      },
    },
  ),
);

/** 向下兼容 hook：接口与旧版 useAuth() 完全一致 */
export function useAuth() {
  const { user, isAuthenticated, isLoading, login, logout } = useAuthStore();
  return { user, isAuthenticated, isLoading, login, logout, token: useAuthStore.getState().token };
}
