import axios from 'axios';

// Trading API 需要独立的 baseURL，因为它走不同的路由
// 生产环境: 通过 Next.js rewrite /api/trading/* -> Kong -> trading-service
// 开发环境: 通过 Next.js rewrite /api/trading/* -> trading-service
const tradingBaseURL = '/api/trading';

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

tradingClient.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)
);

tradingClient.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 TradingStatus {
  initialized: boolean;
  isActive: boolean;
  buyEnabled: boolean;
  activatedAt: string | null;
  totalShares?: string;
  burnTarget?: string;
  burnPeriodMinutes?: number;
  minuteBurnRate?: string;
  message: string;
}

export interface BurnStatus {
  totalBurned: string;
  targetBurn: string;
  remainingBurn: string;
  burnProgress: string;
  minuteBurnRate: string;
  remainingMinutes: number;
  lastBurnMinute: string | null;
}

export interface BurnRecord {
  id: string;
  burnMinute: string;
  burnAmount: string;
  remainingTarget: string;
  sourceType: 'MINUTE_BURN' | 'SELL_BURN';
  sourceAccountSeq: string | null;
  sourceOrderNo: string | null;
  memo: string | null;
  createdAt: string;
}

export interface BurnRecordsResponse {
  data: BurnRecord[];
  total: number;
}

// ==================== Admin 全局兑换记录类型 ====================

export interface AdminOrder {
  id: string;
  orderNo: string;
  accountSequence: string;
  type: 'BUY' | 'SELL';
  status: 'PENDING' | 'PARTIAL' | 'FILLED' | 'CANCELLED';
  source: 'USER' | 'MARKET_MAKER' | 'DEX_BOT' | 'SYSTEM';
  sourceLabel: string | null;
  price: string;
  quantity: string;
  filledQuantity: string;
  remainingQuantity: string;
  averagePrice: string;
  totalAmount: string;
  burnQuantity: string;
  burnMultiplier: string;
  effectiveQuantity: string;
  createdAt: string;
  completedAt: string | null;
  cancelledAt: string | null;
}

export interface AdminTrade {
  id: string;
  tradeNo: string;
  buyOrderId: string;
  sellOrderId: string;
  buyerSequence: string;
  sellerSequence: string;
  price: string;
  quantity: string;
  originalQuantity: string;
  burnQuantity: string;
  amount: string;
  fee: string;
  buyerSource: string;
  sellerSource: string;
  createdAt: string;
}

export interface AdminPaginatedResponse<T> {
  data: T[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

export interface AdminOrdersParams {
  page?: number;
  pageSize?: number;
  type?: 'BUY' | 'SELL';
  status?: 'PENDING' | 'PARTIAL' | 'FILLED' | 'CANCELLED';
  source?: 'USER' | 'MARKET_MAKER' | 'DEX_BOT' | 'SYSTEM';
  search?: string;
  startDate?: string;
  endDate?: string;
}

export interface AdminTradesParams {
  page?: number;
  pageSize?: number;
  source?: 'USER' | 'MARKET_MAKER' | 'DEX_BOT' | 'SYSTEM';
  search?: string;
  startDate?: string;
  endDate?: string;
}

export const tradingApi = {
  // 获取交易系统状态
  getTradingStatus: async (): Promise<TradingStatus> => {
    const response = await tradingClient.get('/admin/trading/status');
    // 后端返回 { success, data, timestamp }
    return response.data.data || response.data;
  },

  // 激活交易系统
  activateTrading: async (): Promise<{ success: boolean; message: string; activatedAt?: string }> => {
    const response = await tradingClient.post('/admin/trading/activate');
    return response.data;
  },

  // 关闭交易系统
  deactivateTrading: async (): Promise<{ success: boolean; message: string }> => {
    const response = await tradingClient.post('/admin/trading/deactivate');
    return response.data;
  },

  // 获取买入功能开关状态
  getBuyEnabled: async (): Promise<{ enabled: boolean }> => {
    const response = await tradingClient.get('/admin/trading/buy-enabled');
    return response.data;
  },

  // 设置买入功能开关
  setBuyEnabled: async (enabled: boolean): Promise<{ success: boolean; enabled: boolean; message: string }> => {
    const response = await tradingClient.post('/admin/trading/buy-enabled', { enabled });
    return response.data;
  },

  // 获取销毁状态
  getBurnStatus: async (): Promise<BurnStatus> => {
    const response = await tradingClient.get('/burn/status');
    // 后端返回 { success, data, timestamp }
    return response.data.data || response.data;
  },

  // 获取销毁记录
  getBurnRecords: async (
    page: number = 1,
    pageSize: number = 20,
    sourceType?: 'MINUTE_BURN' | 'SELL_BURN'
  ): Promise<BurnRecordsResponse> => {
    const params = new URLSearchParams({
      page: page.toString(),
      pageSize: pageSize.toString(),
    });
    if (sourceType) {
      params.append('sourceType', sourceType);
    }
    const response = await tradingClient.get(`/burn/records?${params.toString()}`);
    // 后端返回 { success, data: { data: [...], total: number }, timestamp }
    return response.data.data || response.data;
  },

  // 获取全局订单列表 (admin)
  getAdminOrders: async (params: AdminOrdersParams): Promise<AdminPaginatedResponse<AdminOrder>> => {
    const response = await tradingClient.get('/admin/orders', { params });
    return response.data.data || response.data;
  },

  // 获取全局成交记录 (admin)
  getAdminTrades: async (params: AdminTradesParams): Promise<AdminPaginatedResponse<AdminTrade>> => {
    const response = await tradingClient.get('/admin/trades', { params });
    return response.data.data || response.data;
  },

  // 获取市场概览
  getMarketOverview: async (): Promise<{
    price: string;
    greenPoints: string;
    blackHoleAmount: string;
    circulationPool: string;
    effectiveDenominator: string;
    burnMultiplier: string;
    totalShares: string;
    burnTarget: string;
    burnProgress: string;
  }> => {
    const response = await tradingClient.get('/asset/market');
    // 后端返回 { success, data, timestamp }
    return response.data.data;
  },
};
