/**
 * Checkout token utilities
 * Tokens provide order authentication without requiring user login
 */

import { createHmac, randomUUID } from "crypto"
import { env } from "./env"

export interface CheckoutTokenPayload {
  order_id: number
  exp: number
  nonce: string
}

export class CheckoutToken {
  private static SECRET = env.CHECKOUT_TOKEN_SECRET
  private static TTL = Number.parseInt(env.CHECKOUT_TOKEN_TTL_SECONDS, 10) // 15 minutes default

  /**
   * Generate a new checkout token for an order
   */
  static generate(orderId: number): string {
    const payload: CheckoutTokenPayload = {
      order_id: orderId,
      exp: Math.floor(Date.now() / 1000) + this.TTL,
      nonce: randomUUID(),
    }

    const data = JSON.stringify(payload)
    const signature = this.sign(data)

    return Buffer.from(`${data}.${signature}`).toString("base64url")
  }

  /**
   * Verify and decode a checkout token
   */
  static verify(token: string): CheckoutTokenPayload {
    try {
      const decoded = Buffer.from(token, "base64url").toString("utf-8")
      const [data, signature] = decoded.split(".")

      // Verify signature
      const expectedSignature = this.sign(data)
      if (signature !== expectedSignature) {
        throw new Error("Invalid token signature")
      }

      const payload: CheckoutTokenPayload = JSON.parse(data)

      // Check expiration
      if (Date.now() / 1000 > payload.exp) {
        throw new Error("Token expired")
      }

      return payload
    } catch (error) {
      throw new Error("Invalid checkout token")
    }
  }

  /**
   * Sign data using HMAC-SHA256
   */
  private static sign(data: string): string {
    return createHmac("sha256", this.SECRET).update(data).digest("hex")
  }
}
