"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// src/index.ts
var import_axios = __toESM(require("axios"));

// src/types/token.ts
var SupportedToken = /* @__PURE__ */ ((SupportedToken2) => {
  SupportedToken2["USDT"] = "USDT";
  return SupportedToken2;
})(SupportedToken || {});
var TOKEN_ADDRESSES = {
  // [SupportedToken.USDC]: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T',
  ["USDT" /* USDT */]: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"
};
var TOKEN_DECIMALS = {
  // [SupportedToken.USDC]: 6, // USDC has 6 decimal places
  ["USDT" /* USDT */]: 6
  // USDT has 6 decimal places
};
var TokenUtils = class {
  /**
   * Get the SPL token address from a token enum
   */
  static getTokenAddress(token) {
    return TOKEN_ADDRESSES[token];
  }
  /**
   * Get token enum from SPL address
   */
  static getTokenFromAddress(address) {
    for (const [token, addr] of Object.entries(TOKEN_ADDRESSES)) {
      if (addr === address) {
        return token;
      }
    }
    return null;
  }
  /**
   * Get the number of decimal places for a given token
   */
  static getTokenDecimals(token) {
    return TOKEN_DECIMALS[token] || 6;
  }
  /**
   * Check if a token is supported
   */
  static isTokenSupported(token) {
    return Object.values(SupportedToken).includes(token);
  }
  /**
   * Get the default token (USDT)
   */
  static getDefaultToken() {
    return "USDT" /* USDT */;
  }
};

// src/modules/payments.ts
var PaymentsModule = class {
  constructor(client) {
    this.client = client;
  }
  // --- Product Methods ---
  async createProduct(payload) {
    const requestPayload = { ...payload };
    if (requestPayload.token && !requestPayload.splTokenAddress) {
      requestPayload.splTokenAddress = TokenUtils.getTokenAddress(requestPayload.token);
    }
    if (requestPayload.price) {
      const token = requestPayload.token || "USDT" /* USDT */;
      const decimals = TokenUtils.getTokenDecimals(token);
      const priceValue = typeof requestPayload.price === "string" ? parseFloat(requestPayload.price) : requestPayload.price;
      const priceInBaseUnits = Math.round(priceValue * 10 ** decimals);
      requestPayload.price = priceInBaseUnits.toString();
    }
    const response = await this.client.post("/v1/products", requestPayload);
    return response.data;
  }
  async getProduct(productId) {
    const response = await this.client.get(`/v1/products/${productId}`);
    return response.data;
  }
  async listProducts() {
    const response = await this.client.get("/v1/products");
    return response.data;
  }
  async updateProduct(productId, payload) {
    const requestPayload = { ...payload };
    if (requestPayload.token && !requestPayload.splTokenAddress) {
      requestPayload.splTokenAddress = TokenUtils.getTokenAddress(requestPayload.token);
    }
    const response = await this.client.put(
      `/v1/products/${productId}`,
      requestPayload
    );
    return response.data;
  }
  async deleteProduct(productId) {
    await this.client.delete(`/v1/products/${productId}`);
  }
  // --- Invoice Methods ---
  async createInvoice(payload) {
    const requestPayload = { ...payload };
    if ("token" in requestPayload && !("splTokenAddress" in requestPayload)) {
      requestPayload.splTokenAddress = TokenUtils.getTokenAddress(requestPayload.token);
    }
    const response = await this.client.post("/v1/invoices", requestPayload);
    return response.data;
  }
  async getInvoice(invoiceId) {
    const response = await this.client.get(`/v1/invoices/${invoiceId}`);
    return response.data;
  }
  async listInvoices() {
    const response = await this.client.get("/v1/invoices");
    return response.data;
  }
  async deleteInvoice(invoiceId) {
    await this.client.delete(`/v1/invoices/${invoiceId}`);
  }
};

// src/index.ts
var BeepClient = class {
  constructor(options) {
    this.client = import_axios.default.create({
      baseURL: options.serverUrl || "https://api.beep.com",
      // Default to production URL
      headers: {
        "Authorization": `Bearer ${options.apiKey}`,
        "Content-Type": "application/json"
      }
    });
    this.payments = new PaymentsModule(this.client);
  }
  /**
   * The simplest way to request a payment. 
   * This one-stop method creates an invoice and prepares it for payment.
   * @param payload The details of the charge.
   * @returns A promise that resolves to the created invoice.
   */
  /**
   * Converts a decimal amount to base units based on token decimals
   * @param amount The decimal amount (e.g., 0.01)
   * @param token The token type
   * @returns The amount in base units as an integer (e.g., 10000 for 0.01 USDT)
   */
  convertAmountToBaseUnits(amount, token) {
    const decimals = TOKEN_DECIMALS[token] || 6;
    return Math.round(amount * Math.pow(10, decimals));
  }
  async requestPayment(payload) {
    const requestBody = {
      description: payload.description || "Payment request"
      // Provide a default description
    };
    const token = payload.token || "USDT" /* USDT */;
    if (payload.splTokenAddress) {
      requestBody.splTokenAddress = payload.splTokenAddress;
    } else {
      requestBody.token = token;
    }
    requestBody.amount = this.convertAmountToBaseUnits(payload.amount, token);
    if (payload.payerType) {
      requestBody.payerType = payload.payerType;
    }
    try {
      const response = await this.client.post("/v1/payment/request-payment", requestBody);
      if (!response.data) {
        throw new Error("No data returned from payment request");
      }
      return response.data;
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      throw new Error(`Failed to request payment: ${errorMessage}`);
    }
  }
  // Example function
  async healthCheck() {
    try {
      const response = await this.client.get("/healthz");
      return response.data;
    } catch (error) {
      if (import_axios.default.isAxiosError(error)) {
        throw new Error(`API Error: ${error.response?.data?.message || error.message}`);
      } else {
        throw new Error("An unexpected error occurred.");
      }
    }
  }
};

// tests/integration.test.ts
describe.skip("Integration Tests", () => {
  let client;
  beforeAll(() => {
    client = new BeepClient({
      apiKey: process.env.BEEP_API_KEY || "test-api-key",
      serverUrl: process.env.BEEP_API_URL || "https://34351e6fd33a.ngrok-free.app"
    });
  });
  it("healthCheck should return health status", async () => {
    const health = await client.healthCheck();
    expect(health).toBeDefined();
  });
  it("requestPayment creates a valid invoice", async () => {
    const invoice = await client.requestPayment({
      amount: 0.01,
      // Small amount for testing
      token: "USDT" /* USDT */,
      description: "Integration test payment",
      payerType: "customer_wallet"
    });
    console.log("Invoice created in requestPayment:", invoice);
    expect(invoice).toBeDefined();
    expect(invoice.invoiceId).toBeDefined();
  });
  it("payments module can create and retrieve a product", async () => {
    const product = await client.payments.createProduct({
      name: `Test Product ${Date.now()}`,
      // Unique name
      description: "Created by integration test",
      price: "0.01",
      token: "USDT" /* USDT */,
      isSubscription: false
    });
    expect(product).toBeDefined();
    expect(product.id).toBeDefined();
    const retrievedProduct = await client.payments.getProduct(product.id);
    expect(retrievedProduct).toBeDefined();
    expect(retrievedProduct.id).toBe(product.id);
    await client.payments.deleteProduct(product.id);
  });
  it("payments module should create and get an invoice", async () => {
    const product = await client.payments.createProduct({
      name: "Integration Test Product",
      price: "0.01",
      token: "USDT" /* USDT */,
      description: "Test product for integration tests"
    });
    const invoice = await client.payments.createInvoice({
      productId: product.id,
      payerType: "customer_wallet"
    });
    console.log("Invoice created:", invoice);
    expect(invoice).toBeDefined();
    expect(invoice.id).toBeDefined();
    const invoiceId = invoice.id;
    expect(invoiceId).toBeDefined();
    const retrievedInvoice = await client.payments.getInvoice(invoiceId);
    console.log("Invoice retrieved:", retrievedInvoice);
    expect(retrievedInvoice.id).toBe(invoiceId);
    await client.payments.deleteInvoice(invoiceId);
  }, 1e4);
});
