import axios from 'axios';

// Mining Service API 客户端
// 生产环境: /api/mining/* -> Kong /api/v2/mining/* -> mining-service /api/v2/*
// 开发环境: /api/mining/* -> mining-service /api/v2/*
// 注意: Kong 的路由是 /api/v2/mining/* 映射到 mining-service 的 /api/v2/*
// 所以前端调用 /api/mining/admin/mining/status 会被转发到 mining-service 的 /api/v2/admin/mining/status
const miningBaseURL = '/api/mining';

const miningClient = axios.create({
  baseURL: miningBaseURL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

miningClient.interceptors.request.use(
  (config) => {
    const token = typeof window !== 'undefined' ? localStorage.getItem('admin_token') : null;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

miningClient.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('admin_token');
      if (typeof window !== 'undefined' && !window.location.pathname.includes('/login')) {
        window.location.href = '/login';
      }
    }
    return Promise.reject(error);
  }
);

export interface MiningStatus {
  totalDistributed: string;      // 已分配总量
  distributionPool: string;      // 分配池总量 (2亿)
  remainingDistribution: string; // 剩余分配量
  miningProgress: string;        // 进度百分比
  minuteDistribution: string;    // 每分钟分配量
  remainingMinutes: number;      // 预估剩余分钟数
  lastMiningMinute: string | null; // 最后分配时间
  isActive: boolean;             // 系统是否激活
  currentEra: number;            // 当前纪元
}

export const miningApi = {
  // 获取挖矿进度状态
  getMiningStatus: async (): Promise<MiningStatus> => {
    const response = await miningClient.get('/progress');
    // 后端返回 { success, data, timestamp }
    return response.data.data || response.data;
  },
};
