import { SquareClient } from "square";

// Initialize Square client with production credentials
const client = new SquareClient({
  accessToken: process.env.SQUARE_ACCESS_TOKEN,
} as any);

export interface CreatePaymentRequest {
  sourceId: string;
  amount: number;
  currency: string;
  idempotencyKey: string;
  customerId?: string;
  orderId?: string;
  referenceId?: string;
  note?: string;
}

/**
 * Create a payment using Square API
 */
export async function createPayment(request: CreatePaymentRequest) {
  try {
    const response = await (client.payments as any).createPayment({
      sourceId: request.sourceId,
      idempotencyKey: request.idempotencyKey,
      amountMoney: {
        amount: request.amount, // Amount in cents as number, not BigInt
        currency: request.currency,
      },
      customerId: request.customerId,
      orderId: request.orderId,
      referenceId: request.referenceId,
      note: request.note,
      locationId: process.env.SQUARE_LOCATION_ID,
    });

    // Serialize response to avoid BigInt JSON errors
    const payment = (response as any).result?.payment;
    return {
      success: true,
      paymentId: payment?.id || null,
      status: payment?.status || null,
      receiptUrl: payment?.receiptUrl || null,
      data: payment ? JSON.parse(JSON.stringify(payment, (key, value) => 
        typeof value === 'bigint' ? value.toString() : value
      )) : null,
    };
  } catch (error: any) {
    console.error("[Square] Payment creation error:", error.message);
    return {
      success: false,
      error: error.message,
    };
  }
}

/**
 * Retrieve payment details
 */
export async function getPayment(paymentId: string) {
  try {
    const response = await (client.payments as any).retrievePayment(paymentId);
    return {
      success: true,
      data: (response as any).result?.payment,
    };
  } catch (error: any) {
    console.error("[Square] Get payment error:", error.message);
    return {
      success: false,
      error: error.message,
    };
  }
}

/**
 * Refund a payment
 */
export async function refundPayment(paymentId: string, amount: number, currency: string) {
  try {
    const response = await (client.refunds as any).refundPayment({
      paymentId,
      idempotencyKey: `refund-${paymentId}-${Date.now()}`,
      amountMoney: {
        amount: amount, // Amount in cents as number, not BigInt
        currency,
      },
    });

    // Serialize response to avoid BigInt JSON errors
    const refund = (response as any).result?.refund;
    return {
      success: true,
      refundId: refund?.id || null,
      status: refund?.status || null,
      data: refund ? JSON.parse(JSON.stringify(refund, (key, value) => 
        typeof value === 'bigint' ? value.toString() : value
      )) : null,
    };
  } catch (error: any) {
    console.error("[Square] Refund error:", error.message);
    return {
      success: false,
      error: error.message,
    };
  }
}
