import React, { createContext, useState, useRef, useCallback, useEffect, useContext } from 'react';

// src/auth/legacy/contexts/AuthContext.tsx
var AuthContext = createContext(void 0);
function extractUser(data) {
  return data?.user ?? data?.data?.user ?? null;
}
function extractValid(data) {
  if (typeof data?.valid === "boolean") return data.valid;
  if (typeof data?.data?.valid === "boolean") return data.data.valid;
  return false;
}
function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const isMountedRef = useRef(true);
  const safeSetState = useCallback((updater) => {
    if (isMountedRef.current) {
      updater();
    }
  }, []);
  const validateSession = useCallback(async () => {
    console.log("\u{1F50D} [AuthContext] \u5F00\u59CB\u9A8C\u8BC1\u4F1A\u8BDD...");
    try {
      const response = await fetch("/api/auth/validate");
      console.log("\u{1F4E1} [AuthContext] \u4F1A\u8BDD\u9A8C\u8BC1\u54CD\u5E94\u72B6\u6001:", response.status);
      const data = await response.json();
      console.log("\u{1F4C4} [AuthContext] \u4F1A\u8BDD\u9A8C\u8BC1\u54CD\u5E94\u6570\u636E:", data);
      const resolvedUser = extractUser(data);
      const resolvedValid = extractValid(data);
      safeSetState(() => {
        if (resolvedValid && resolvedUser) {
          console.log("\u2705 [AuthContext] \u4F1A\u8BDD\u9A8C\u8BC1\u6210\u529F, \u7528\u6237:", resolvedUser);
          setUser(resolvedUser);
          setIsAuthenticated(true);
        } else {
          console.log("\u274C [AuthContext] \u4F1A\u8BDD\u9A8C\u8BC1\u5931\u8D25:", data.message);
          setUser(null);
          setIsAuthenticated(false);
        }
        setLoading(false);
      });
    } catch (error) {
      console.error("\u{1F4A5} [AuthContext] \u4F1A\u8BDD\u9A8C\u8BC1\u5F02\u5E38:", error);
      safeSetState(() => {
        setUser(null);
        setIsAuthenticated(false);
        setLoading(false);
      });
    }
  }, [safeSetState]);
  const login = useCallback(async (credentials) => {
    console.log("\u{1F511} [AuthContext] \u5F00\u59CB\u767B\u5F55...");
    console.log("\u{1F4DD} [AuthContext] \u767B\u5F55\u51ED\u636E:", { phone: credentials.phone, password: "***" });
    try {
      console.log("\u{1F4E4} [AuthContext] \u53D1\u9001\u767B\u5F55\u8BF7\u6C42\u5230 /api/auth/login");
      const response = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(credentials)
      });
      console.log("\u{1F4E1} [AuthContext] \u6536\u5230\u54CD\u5E94\uFF0C\u72B6\u6001\u7801:", response.status);
      const data = await response.json();
      console.log("\u{1F4C4} [AuthContext] \u54CD\u5E94\u6570\u636E:", data);
      const resolvedUser = extractUser(data);
      if (data.success && resolvedUser) {
        console.log("\u2705 [AuthContext] \u767B\u5F55\u6210\u529F, \u5F00\u59CB\u66F4\u65B0\u5168\u5C40\u72B6\u6001");
        console.log("\u{1F464} [AuthContext] \u7528\u6237\u6570\u636E:", resolvedUser);
        console.log("\u{1F4CA} [AuthContext] \u66F4\u65B0\u524D\u72B6\u6001:", {
          currentUser: user ? `${user.name || "\u672A\u8BBE\u7F6E"} (${user.phone})` : null,
          currentIsAuthenticated: isAuthenticated,
          currentLoading: loading
        });
        console.log("\u{1F504} [AuthContext] \u6267\u884C\u5168\u5C40\u72B6\u6001\u66F4\u65B0...");
        safeSetState(() => {
          console.log("\u{1F504} [AuthContext] \u6B63\u5728\u8BBE\u7F6E\u7528\u6237:", resolvedUser);
          setUser(resolvedUser);
          console.log("\u{1F504} [AuthContext] \u6B63\u5728\u8BBE\u7F6E\u8BA4\u8BC1\u72B6\u6001: true");
          setIsAuthenticated(true);
          console.log("\u{1F504} [AuthContext] \u6B63\u5728\u8BBE\u7F6E\u52A0\u8F7D\u72B6\u6001: false");
          setLoading(false);
          console.log("\u2705 [AuthContext] \u5168\u5C40\u72B6\u6001\u66F4\u65B0\u5B8C\u6210");
        });
        setTimeout(() => {
          console.log("\u{1F389} [AuthContext] \u5EF6\u8FDF\u786E\u8BA4 - \u5168\u5C40\u767B\u5F55\u72B6\u6001\u5E94\u8BE5\u5DF2\u66F4\u65B0:", {
            user: resolvedUser,
            isAuthenticated: true
          });
        }, 0);
        console.log("\u{1F680} [AuthContext] \u8FD4\u56DE\u6210\u529F\u7ED3\u679C");
        return { success: true, user: resolvedUser };
      } else {
        console.log("\u274C [AuthContext] \u767B\u5F55\u5931\u8D25:", data.message);
        return { success: false, message: data.message };
      }
    } catch (error) {
      console.error("\u{1F4A5} [AuthContext] \u767B\u5F55\u5F02\u5E38:", error);
      return { success: false, message: "\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" };
    }
  }, [safeSetState, user, isAuthenticated, loading]);
  const register = useCallback(async (userData) => {
    console.log("\u{1F4DD} [AuthContext] \u5F00\u59CB\u6CE8\u518C...");
    try {
      const response = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(userData)
      });
      const data = await response.json();
      console.log("\u{1F4E1} [AuthContext] \u6CE8\u518C\u54CD\u5E94:", data);
      const resolvedUser = extractUser(data);
      if (data.success && resolvedUser) {
        console.log("\u2705 [AuthContext] \u6CE8\u518C\u6210\u529F, \u7ACB\u5373\u66F4\u65B0\u5168\u5C40\u72B6\u6001");
        safeSetState(() => {
          setUser(resolvedUser);
          setIsAuthenticated(true);
          setLoading(false);
        });
        console.log("\u{1F680} [AuthContext] \u8FD4\u56DE\u6CE8\u518C\u6210\u529F\u7ED3\u679C");
        return { success: true, user: resolvedUser };
      } else {
        console.log("\u274C [AuthContext] \u6CE8\u518C\u5931\u8D25:", data.message);
        return { success: false, message: data.message };
      }
    } catch (error) {
      console.error("\u{1F4A5} [AuthContext] \u6CE8\u518C\u5F02\u5E38:", error);
      return { success: false, message: "\u6CE8\u518C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" };
    }
  }, [safeSetState]);
  const logout = useCallback(async () => {
    console.log("\u{1F6AA} [AuthContext] \u5F00\u59CB\u767B\u51FA...");
    try {
      await fetch("/api/auth/logout", { method: "POST" });
      safeSetState(() => {
        setUser(null);
        setIsAuthenticated(false);
      });
      console.log("\u2705 [AuthContext] \u767B\u51FA\u6210\u529F, \u5168\u5C40\u72B6\u6001\u5DF2\u6E05\u9664");
    } catch (error) {
      console.error("\u{1F4A5} [AuthContext] \u767B\u51FA\u5931\u8D25:", error);
    }
  }, [safeSetState]);
  const refreshUser = useCallback(() => {
    console.log("\u{1F504} [AuthContext] \u5237\u65B0\u7528\u6237\u4FE1\u606F...");
    setLoading(true);
    validateSession();
  }, [validateSession]);
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);
  useEffect(() => {
    console.log("\u{1F680} [AuthContext] \u521D\u59CB\u5316, \u5F00\u59CB\u9A8C\u8BC1\u4F1A\u8BDD");
    validateSession();
  }, [validateSession]);
  useEffect(() => {
    console.log("\u{1F4CA} [AuthContext] \u5168\u5C40\u72B6\u6001\u53D8\u5316:", {
      isAuthenticated,
      user: user ? `${user.name || "\u672A\u8BBE\u7F6E"} (${user.phone})` : null,
      loading
    });
  }, [isAuthenticated, user, loading]);
  const value = {
    user,
    loading,
    isAuthenticated,
    login,
    register,
    logout,
    refreshUser
  };
  return /* @__PURE__ */ React.createElement(AuthContext.Provider, { value }, children);
}
function useAuth() {
  const context = useContext(AuthContext);
  if (context === void 0) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
}

// src/auth/legacy/types/index.ts
var UserRole = /* @__PURE__ */ ((UserRole2) => {
  UserRole2["USER"] = "user";
  UserRole2["ADMIN"] = "admin";
  return UserRole2;
})(UserRole || {});

// src/auth/legacy/utils/authUtils.ts
function validatePhoneNumber(phone) {
  return /^1[3-9]\d{9}$/.test(phone);
}
function validatePassword(password) {
  if (!password) {
    return { valid: false, message: "\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A" };
  }
  if (password.length < 6) {
    return { valid: false, message: "\u5BC6\u7801\u957F\u5EA6\u81F3\u5C116\u4F4D" };
  }
  return { valid: true };
}
function generateSessionToken() {
  return Math.random().toString(36).substring(2) + Date.now().toString(36) + Math.random().toString(36).substring(2);
}
function isAdmin(user) {
  return user?.role === "admin";
}
function isActiveUser(user) {
  return user?.isActive === true;
}
function getUserDisplayName(user) {
  return user.name || user.phone || "\u672A\u77E5\u7528\u6237";
}
function calculateSessionExpiry(days = 30) {
  return new Date(Date.now() + days * 24 * 60 * 60 * 1e3);
}
function isSessionExpired(expiresAt) {
  return /* @__PURE__ */ new Date() > new Date(expiresAt);
}

export { AuthProvider, UserRole, calculateSessionExpiry, generateSessionToken, getUserDisplayName, isActiveUser, isAdmin, isSessionExpired, useAuth, validatePassword, validatePhoneNumber };
//# sourceMappingURL=index.mjs.map
//# sourceMappingURL=index.mjs.map