type QueueSender = { send: (message: unknown) => Promise<void> }

export class QueueDataPusher {
  private getEnv() {
    return (globalThis as {
      ENV?: {
        NOTIF_QUEUE?: QueueSender
        ORDER_PLACED_QUEUE?: QueueSender
        ORDER_CANCELLED_QUEUE?: QueueSender
      }
    }).ENV
  }

  async pushNotifQueue(message: unknown): Promise<boolean> {
    const env = this.getEnv()
    if (!env?.NOTIF_QUEUE) {
      console.warn('NOTIF_QUEUE binding not available, skipping enqueue')
      return false
    }
    await env.NOTIF_QUEUE.send(message)
    return true
  }

  async pushOrderPlacedQueue(message: { name: 'order-placed'; orderIds: number[] }): Promise<boolean> {
    const env = this.getEnv()
    if (!env?.ORDER_PLACED_QUEUE) {
      console.warn('ORDER_PLACED_QUEUE binding not available, skipping publish')
      return false
    }
    await env.ORDER_PLACED_QUEUE.send(message)
    return true
  }

  async pushOrderCancelledQueue(message: {
    name: 'order-cancelled'
    orderId: number
    cancelledBy: 'user' | 'admin'
    reason: string
    cancelledAt: string
  }): Promise<boolean> {
    const env = this.getEnv()
    if (!env?.ORDER_CANCELLED_QUEUE) {
      console.warn('ORDER_CANCELLED_QUEUE binding not available, skipping publish')
      return false
    }
    await env.ORDER_CANCELLED_QUEUE.send(message)
    return true
  }
}

export const queueDataPusher = new QueueDataPusher()
