// Initialize HelcimPay.js session
import { requireAuth } from "../../utils/auth.js";

const HELCIM_API_BASE = "https://api.helcim.com/v2";

export default defineEventHandler(async (event) => {
  try {
    const config = useRuntimeConfig(event);
    const body = await validateBody(event, helcimInitializePaymentSchema);

    // Event ticket purchases can be made without authentication
    const isEventTicket = body.metadata?.type === "event_ticket";
    if (!isEventTicket) {
      await requireAuth(event);
    }

    const helcimToken = config.helcimApiToken;
    const amount = body.amount || 0;

    // For event tickets with amount > 0, we do a purchase
    // For subscriptions or card verification, we do verify
    const paymentType = isEventTicket && amount > 0 ? "purchase" : "verify";

    const requestBody = {
      paymentType,
      amount: paymentType === "purchase" ? amount : 0,
      currency: "CAD",
      paymentMethod: "cc",
    };

    // For subscription setup (verify mode), include customer code if provided
    // For one-time purchases (event tickets), don't include customer code
    // as the customer may not exist in Helcim yet
    if (body.customerCode && paymentType === "verify") {
      requestBody.customerCode = body.customerCode;
    }

    // Add product/event information for better display in Helcim modal
    if (body.metadata?.eventTitle) {
      // Some Helcim accounts don't support invoice numbers in initialization
      // Try multiple fields that might display in the modal
      requestBody.description = body.metadata.eventTitle;
      requestBody.notes = body.metadata.eventTitle;
      requestBody.orderNumber = `${body.metadata.eventId}`;
    }

    // Initialize HelcimPay.js session
    const response = await fetch(`${HELCIM_API_BASE}/helcim-pay/initialize`, {
      method: "POST",
      headers: {
        accept: "application/json",
        "content-type": "application/json",
        "api-token": helcimToken,
      },
      body: JSON.stringify(requestBody),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error(
        "HelcimPay initialization failed:",
        response.status,
        errorText,
      );
      throw createError({
        statusCode: response.status,
        statusMessage: 'Payment initialization failed',
      });
    }

    const paymentData = await response.json();

    return {
      success: true,
      checkoutToken: paymentData.checkoutToken,
      secretToken: paymentData.secretToken,
    };
  } catch (error) {
    if (error.statusCode) throw error;
    console.error("Error initializing HelcimPay:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "An unexpected error occurred",
    });
  }
});
