/**
 * H5 用户端认证状态管理
 * - 与后台管理独立，使用不同 token
 * - localStorage key 使用 h5_ 前缀避免冲突
 */
import { create } from 'zustand';
import { h5Api, type H5User } from './api';

const TOKEN_KEY = 'h5_token';
const USER_KEY = 'h5_user';

interface AuthState {
  token: string | null;
  user: H5User | null;
  loading: boolean;
  isAuthenticated: boolean;
  login: (phone: string, password: string) => Promise<void>;
  logout: () => void;
  restore: () => void;
}

export const useH5AuthStore = create<AuthState>((set) => ({
  token: null,
  user: null,
  loading: false,
  isAuthenticated: false,

  login: async (phone: string, password: string) => {
    set({ loading: true });
    try {
      const res = await h5Api.login({ phone, password });
      const { token, user } = res.data;
      localStorage.setItem(TOKEN_KEY, token);
      localStorage.setItem(USER_KEY, JSON.stringify(user));
      set({ token, user, isAuthenticated: true, loading: false });
    } catch {
      set({ loading: false });
      throw new Error('登录失败，请检查手机号和密码');
    }
  },

  logout: () => {
    localStorage.removeItem(TOKEN_KEY);
    localStorage.removeItem(USER_KEY);
    set({ token: null, user: null, isAuthenticated: false });
  },

  restore: () => {
    const token = localStorage.getItem(TOKEN_KEY);
    const raw = localStorage.getItem(USER_KEY);
    if (token) {
      const user = raw ? JSON.parse(raw) as H5User : null;
      set({ token, user, isAuthenticated: true });
    }
  },
}));
