import axios from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";
import { Logs } from "./logs.js";

const BaseURL = {
  pinnacle: "https://api.pinnacle888.com",
  pstery: "http://127.0.0.1:9055",
}

export const pinnacleRequest = async (options) => {
  const {
    endpoint,
    params = {},
    username,
    password,
    method = "GET",
    data,
    proxy,
    timeout = 10000,
  } = options;

  if (!endpoint || !username || !password) {
    throw new Error("endpoint、username、password is required");
  }

  const authHeader = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;

  const axiosConfig = {
    baseURL: BaseURL.pinnacle,
    url: endpoint,
    method,
    headers: {
      "Authorization": authHeader,
      "Accept": "application/json",
      "Content-Type": "application/json",
    },
    params,
    data,
    timeout,
  };

  if (proxy) {
    axiosConfig.proxy = false;
    axiosConfig.httpsAgent = new HttpsProxyAgent(proxy);
  }

  return axios(axiosConfig).then(res => res.data);

}

export const getPsteryRelations = async (mk=-1) => {
  const axiosConfig = {
    baseURL: BaseURL.pstery,
    url: '/api/pstery/get_games_relation',
    method: 'GET',
    params: {
      mk,
    },
    proxy: false,
  };

  return axios(axiosConfig).then(res => res.data);
}

export const updateBaseEvents = async (data) => {
  const axiosConfig = {
    baseURL: BaseURL.pstery,
    url: '/api/pstery/update_base_events',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    data: JSON.stringify(data),
    proxy: false,
  };

  axios(axiosConfig).then(res => res.data)
  .then(() => {
    Logs.outDev('update base events success', data);
  })
  .catch(err => {
    Logs.err('failed to update base events:', err.message);
  });
}

export const notifyException = async (message) => {
  const axiosConfig = {
    baseURL: BaseURL.pstery,
    url: '/api/pstery/notify_exception',
    method: 'POST',
    data: { message },
    proxy: false,
  };
  axios(axiosConfig).then(res => res.data)
  .then(() => {
    Logs.out('notify exception success');
  })
  .catch(err => {
    Logs.err('failed to notify exception:', err.message);
  });
}