import { json } from "@sveltejs/kit";
async function POST({ request }) {
  try {
    const payload = await request.json();
    console.log("Received Tebex webhook:", payload.type);
    switch (payload.type) {
      case "payment.completed":
        await handlePaymentCompleted(payload);
        break;
      case "payment.refunded":
        await handlePaymentRefunded(payload);
        break;
      case "payment.disputed":
        await handlePaymentDisputed(payload);
        break;
      default:
        console.log("Unhandled webhook type:", payload.type);
    }
    return json({ received: true }, { status: 200 });
  } catch (error) {
    console.error("Webhook processing error:", error);
    return json({ error: "Processing error" }, { status: 200 });
  }
}
async function handlePaymentCompleted(payload) {
  console.log("Payment completed:", payload.payment_id);
  const mcusername = payload.custom?.mcusername;
  payload.custom?.timestamp;
  const products = payload.products || [];
  const customer = payload.customer || {};
  const payment = payload.payment || {};
  console.log("Customer:", customer.email);
  console.log("Minecraft Username:", mcusername);
  console.log("Products purchased:", products.map((p) => p.name).join(", "));
  for (const product of products) {
    await processPurchase({
      mcusername,
      productName: product.name,
      productId: product.id,
      quantity: product.quantity,
      price: product.price,
      paymentId: payment.id,
      transactionId: payment.gateway_id,
      customerEmail: customer.email
    });
  }
}
async function handlePaymentRefunded(payload) {
  console.log("Payment refunded:", payload.payment_id);
  const mcusername = payload.custom?.mcusername;
  const products = payload.products || [];
  for (const product of products) {
    await revokePurchase({
      mcusername,
      productName: product.name,
      reason: "refund"
    });
  }
}
async function handlePaymentDisputed(payload) {
  console.log("Payment disputed:", payload.payment_id);
  const mcusername = payload.custom?.mcusername;
  const products = payload.products || [];
  for (const product of products) {
    await revokePurchase({
      mcusername,
      productName: product.name,
      reason: "chargeback"
    });
  }
}
async function processPurchase(data) {
  console.log("Processing purchase for", data.mcusername);
  console.log("✓ Purchase processed:", {
    username: data.mcusername,
    product: data.productName
  });
}
async function revokePurchase(data) {
  console.log("Revoking purchase for", data.mcusername, "reason:", data.reason);
  console.log("✓ Purchase revoked:", {
    username: data.mcusername,
    product: data.productName,
    reason: data.reason
  });
}
export {
  POST
};
