/**
 * Security utilities for checkout
 */

import { CheckoutToken } from "./token"
import { WooCommerce } from "./woo"

export interface SecurityContext {
  orderId: number
  nonce: string
}

export class Security {
  /**
   * Verify checkout token and ensure it's valid
   * This prevents token replay attacks
   */
  static async verifyToken(token: string): Promise<SecurityContext> {
    // Decode and verify token signature + expiry
    const payload = CheckoutToken.verify(token)

    // Fetch order from WooCommerce
    const order = await WooCommerce.getOrder(payload.order_id)

    // Check if order can be paid
    if (!WooCommerce.canBePaid(order) && !WooCommerce.isPaid(order)) {
      throw new Error("Order cannot be paid")
    }

    // Check if nonce has already been used (prevent replay attacks)
    const usedNonce = WooCommerce.getMeta(order, "_checkout_nonce")
    const paymentIntentId = WooCommerce.getMeta(order, "_payment_intent_id")
    
    // If nonce already used AND payment completed, token is truly used
    if (usedNonce === payload.nonce && WooCommerce.isPaid(order)) {
      // Order is paid, allow for status checks only
      return {
        orderId: payload.order_id,
        nonce: payload.nonce,
      }
    }
    
    // If payment intent exists but order not paid yet, allow retry
    // This handles cases where user refreshes during payment
    if (usedNonce === payload.nonce && paymentIntentId) {
      return {
        orderId: payload.order_id,
        nonce: payload.nonce,
      }
    }
    
    // If nonce used but no payment intent, something went wrong - allow retry
    if (usedNonce === payload.nonce && !paymentIntentId && WooCommerce.canBePaid(order)) {
      return {
        orderId: payload.order_id,
        nonce: payload.nonce,
      }
    }

    return {
      orderId: payload.order_id,
      nonce: payload.nonce,
    }
  }

  /**
   * Mark nonce as used in WooCommerce order
   */
  static async markNonceUsed(orderId: number, nonce: string): Promise<void> {
    const order = await WooCommerce.getOrder(orderId)
    const metaData = WooCommerce.setMeta(order, "_checkout_nonce", nonce)

    await WooCommerce.updateOrder(orderId, {
      meta_data: metaData,
    })
  }

  /**
   * Validate that request origin is allowed
   */
  static validateOrigin(request: Request): void {
    // Import here to avoid circular dependency
    const { env } = require("./env")
    const origin = request.headers.get("origin")
    const allowedOrigins = env.ALLOWED_ORIGINS?.split(",") || []

    // if (
    //   env.NODE_ENV === "production" &&
    //   allowedOrigins.length > 0 &&
    //   (!origin || !allowedOrigins.includes(origin))
    // ) {
    //   throw new Error("Invalid origin")
    // }
  }
}
