import axios from 'axios';

const tradingClient = axios.create({
  baseURL: '/api/trading',
  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) => {
    if (response.data && response.data.data !== undefined) {
      response.data = response.data.data;
    }
    return 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 C2cBotStatus {
  success: boolean;
  enabled: boolean;
  blockchainAvailable: boolean;
  hotWallet: {
    address: string | null;
    balance: string | null;
  };
  stats: {
    totalBotOrders: number;
    totalBotAmount: string;
  };
}

export interface BotOrder {
  orderNo: string;
  makerAccountSequence: string;
  makerPhone: string | null;
  makerNickname: string | null;
  totalAmount: string;
  price: string;
  quantity: string;
  sellerKavaAddress: string | null;
  paymentTxHash: string | null;
  status: string;
  completedAt: string | null;
  createdAt: string;
}

export interface BotOrdersResponse {
  success: boolean;
  data: BotOrder[];
  total: number;
  page: number;
  pageSize: number;
}

export const c2cBotApi = {
  getStatus: async (): Promise<C2cBotStatus> => {
    const response = await tradingClient.get('/admin/c2c-bot/status');
    return response.data;
  },

  enable: async (): Promise<{ success: boolean; enabled: boolean; message: string }> => {
    const response = await tradingClient.post('/admin/c2c-bot/enable');
    return response.data;
  },

  disable: async (): Promise<{ success: boolean; enabled: boolean; message: string }> => {
    const response = await tradingClient.post('/admin/c2c-bot/disable');
    return response.data;
  },

  getOrders: async (page: number = 1, pageSize: number = 20): Promise<BotOrdersResponse> => {
    const response = await tradingClient.get('/admin/c2c-bot/orders', {
      params: { page, pageSize },
    });
    return response.data;
  },
};
