import { API_BASE_URL } from "./client";
import { apiClient } from "./client";
import Cookies from 'js-cookie';

/**
 * 邮箱登录响应类型
 */
export interface EmailLoginResponse {
  success: boolean;
  code: number;
  data: {
    token: string;
    is_superuser?: boolean;
    role?: string;
  };
  message: string;
}

/**
 * 邮箱登录接口
 * @param email 邮箱
 * @param password 密码
 * @returns 包含token的响应
 */
export const emailLogin = async (email: string, password: string): Promise<EmailLoginResponse> => {
  try {
    const response = await apiClient.post('/v1/admin/login/', {
      email,
      password,
    });
    
    if (!response.data.success) {
      throw new Error(response.data.message || '登录失败');
    }
    
    return response.data;
  } catch (error) {
    console.error("邮箱登录失败:", error);
    throw error;
  }
};

/**
 * 保存登录凭证到本地存储和Cookie
 * @param token 访问令牌
 */
export const saveAuthToken = (token: string, isSuperUser?: boolean, role?: string): void => {
  // 保存到localStorage
  localStorage.setItem("auth_token", token);

  // 保存超级管理员标识
  if (isSuperUser !== undefined) {
    localStorage.setItem("is_superuser", isSuperUser ? "true" : "false");
  }

  // 保存用户角色
  if (role) {
    localStorage.setItem("user_role", role);
  }

  // 保存到Cookie，以便middleware可以访问
  // 过期时间设为7天
  Cookies.set("auth_token", token, { expires: 7, path: '/' });
};

/**
 * 检查当前用户是否为超级管理员
 * @returns 是否为超级管理员
 */
export const isSuperUser = (): boolean => {
  if (typeof window === "undefined") return false;
  return localStorage.getItem("is_superuser") === "true";
};

/**
 * 获取存储的登录凭证
 * @returns 登录凭证
 */
export const getAuthToken = (): string | null => {
  if (typeof window === "undefined") return null;
  
  // 优先从localStorage获取
  return localStorage.getItem("auth_token");
};

/**
 * 清除登录凭证
 */
export const clearAuthToken = (): void => {
  localStorage.removeItem("auth_token");
  localStorage.removeItem("is_superuser");
  localStorage.removeItem("user_role");
  Cookies.remove("auth_token", { path: '/' });
};

/**
 * 检查用户是否已登录
 * @returns 是否已登录
 */
export const isAuthenticated = (): boolean => {
  return !!getAuthToken();
};

/**
 * 退出登录
 * @returns Promise<void>
 */
export const logout = async (): Promise<void> => {
  try {
    // 获取token
    const token = getAuthToken();
    
    if (token) {
      // 调用退出登录API
      const response = await apiClient.post('/v1/admin/logout/');
      
      if (!response.data.success) {
        console.error("退出登录失败:", response.data.message);
      }
    }
    
    // 清除本地存储的凭证
    clearAuthToken();
    
    // 清除登录状态
    localStorage.removeItem("isLoggedIn");
    
  } catch (error) {
    console.error("退出登录失败:", error);
  }
}; 