///|
/// Cloudflare Workers Queues (`to_queue_handler`) and Cron Triggers (`to_scheduled_handler`)
/// FFI exporters. Maps real JS `msg.ack()` / `msg.retry({ delaySeconds })` and binds `ctx.waitUntil`.

///|
#external
pub type JsQueueBatch

///|
#external
pub type JsQueueMessage

///|
#external
pub type JsScheduledController

///|
/// Outcome returned by a Cloudflare Queue consumer for each message in a batch.
#non_exhaustive
#derive(Debug, Eq)
pub(all) enum QueueAction {
  Ack
  Retry(delay_seconds~ : Int32?)
}

///|
/// Strongly-typed Cloudflare Queue message passed to MoonBit consumers.
#derive(Debug, Eq)
pub(all) struct CfQueueEntry {
  id : String
  queue : String
  timestamp_ms : Int64
  body : Json
  attempts : Int32
}

///|
/// Strongly-typed Cloudflare Cron Trigger event passed to MoonBit scheduled handlers.
#derive(Debug, Eq)
pub(all) struct CfScheduledTrigger {
  cron : String
  scheduled_time_ms : Int64
}

///|
extern "js" fn js_queue_batch_name(batch : JsQueueBatch) -> String =
  #| (b) => String((b && b.queue) || "")

///|
extern "js" fn js_queue_batch_messages(
  batch : JsQueueBatch,
) -> FixedArray[JsQueueMessage] =
  #| (b) => Array.isArray(b && b.messages) ? b.messages : []

///|
extern "js" fn js_queue_msg_id(msg : JsQueueMessage) -> String =
  #| (m) => String((m && m.id) || "")

///|
extern "js" fn js_queue_msg_timestamp_ms(msg : JsQueueMessage) -> Double =
  #| (m) => {
  #|   const ts = m && m.timestamp;
  #|   if (ts instanceof Date) return ts.getTime();
  #|   if (typeof ts === "number") return ts;
  #|   return 0;
  #| }

///|
extern "js" fn js_queue_msg_attempts(msg : JsQueueMessage) -> Int32 =
  #| (m) => ((m && m.attempts) || 1) | 0

///|
extern "js" fn js_queue_msg_body_json(msg : JsQueueMessage) -> String =
  #| (m) => {
  #|   try { return JSON.stringify(m ? m.body : null); } catch (_) { return "null"; }
  #| }

///|
extern "js" fn js_queue_msg_ack(msg : JsQueueMessage) -> Unit =
  #| (m) => { if (m && typeof m.ack === "function") m.ack(); }

///|
extern "js" fn js_queue_msg_retry(
  msg : JsQueueMessage,
  has_delay : Bool,
  delay_seconds : Int32,
) -> Unit =
  #| (m, hasDelay, delaySeconds) => {
  #|   if (m && typeof m.retry === "function") {
  #|     if (hasDelay && delaySeconds > 0) m.retry({ delaySeconds });
  #|     else m.retry();
  #|   }
  #| }

///|
extern "js" fn js_scheduled_cron(ctrl : JsScheduledController) -> String =
  #| (c) => String((c && c.cron) || "")

///|
extern "js" fn js_scheduled_time_ms(ctrl : JsScheduledController) -> Double =
  #| (c) => (c && typeof c.scheduledTime === "number") ? c.scheduledTime : 0

///|
/// Exports a Cloudflare Workers `queue(batch, env, ctx)` handler.
/// Each message's return value (or raised error) drives real JS `msg.ack()` / `msg.retry({ delaySeconds })`,
/// and `ctx.waitUntil` is wired into `@runtime.ExecutionContext` so background tasks drain cleanly.
pub fn to_queue_handler(
  consumer : async (CfQueueEntry, @runtime.Env, @runtime.ExecutionContext) -> QueueAction,
  env_mapper? : (JsEnv) -> @runtime.Env,
) -> (JsQueueBatch, JsEnv, JsExecutionContext) -> @js_async.Promise[Unit] {
  (batch, js_env, js_ctx) => {
    let p = @js_async.Promise::from_async(() => {
      let env = match env_mapper {
        Some(mapper) => mapper(js_env)
        None => @runtime.Env::Env()
      }
      let exec_ctx = @runtime.ExecutionContext::ExecutionContext(schedule_fn=task => {
        let bg = @js_async.Promise::from_async(() => task())
        js_wait_until(js_ctx, bg)
      })
      let queue_name = js_queue_batch_name(batch)
      let raw_msgs = js_queue_batch_messages(batch)
      for i in 0.. Json::null()
        }
        let entry : CfQueueEntry = {
          id: js_queue_msg_id(m),
          queue: queue_name,
          timestamp_ms: js_queue_msg_timestamp_ms(m).to_int64(),
          body: body_json,
          attempts: js_queue_msg_attempts(m),
        }
        try consumer(entry, env, exec_ctx) catch {
          _ => js_queue_msg_retry(m, false, 0)
        } noraise {
          action =>
            match action {
              QueueAction::Ack => js_queue_msg_ack(m)
              QueueAction::Retry(delay_seconds~) =>
                match delay_seconds {
                  Some(sec) => js_queue_msg_retry(m, true, sec)
                  None => js_queue_msg_retry(m, false, 0)
                }
              QueueAction::.. => js_queue_msg_ack(m)
            }
        }
      }
    })
    js_wait_until(js_ctx, p)
    p
  }
}

///|
/// Exports a Cloudflare Workers `scheduled(controller, env, ctx)` Cron Trigger handler,
/// wiring `ctx.waitUntil` so async tasks are never frozen before completion.
pub fn to_scheduled_handler(
  handler : async (CfScheduledTrigger, @runtime.Env, @runtime.ExecutionContext) -> Unit,
  env_mapper? : (JsEnv) -> @runtime.Env,
) -> (JsScheduledController, JsEnv, JsExecutionContext) -> @js_async.Promise[
  Unit,
] {
  (ctrl, js_env, js_ctx) => {
    let p = @js_async.Promise::from_async(() => {
      let env = match env_mapper {
        Some(mapper) => mapper(js_env)
        None => @runtime.Env::Env()
      }
      let exec_ctx = @runtime.ExecutionContext::ExecutionContext(schedule_fn=task => {
        let bg = @js_async.Promise::from_async(() => task())
        js_wait_until(js_ctx, bg)
      })
      let trigger : CfScheduledTrigger = {
        cron: js_scheduled_cron(ctrl),
        scheduled_time_ms: js_scheduled_time_ms(ctrl).to_int64(),
      }
      handler(trigger, env, exec_ctx)
    })
    js_wait_until(js_ctx, p)
    p
  }
}