///|
/// Cloudflare Workers D1Database 原生 JS 绑定句柄
#external
pub type D1Database

///|
extern "js" fn js_d1_query(
  db : D1Database,
  sql : String,
  params_json : String,
  use_bigint_i64 : Bool,
) -> @js_async.Promise[String] =
  #| (db, sql, paramsJson, useBigIntI64) => {
  #|   const decodeParams = (raw) => {
  #|     const arr = JSON.parse(raw);
  #|     return arr.map((p) => {
  #|       if (p === null || p.t === "null") return null;
  #|       if (p.t === "bool") return p.v ? 1 : 0;
  #|       if (p.t === "i32" || p.t === "f64") return p.v;
  #|       if (p.t === "i64") {
  #|         const bi = BigInt(p.v);
  #|         if (bi >= -9007199254740991n && bi <= 9007199254740991n) return Number(bi);
  #|         return useBigIntI64 ? bi : String(p.v);
  #|       }
  #|       if (p.t === "text" || p.t === "json") return p.v;
  #|       if (p.t === "bytes") {
  #|         const bin = atob(p.v);
  #|         const u8 = new Uint8Array(bin.length);
  #|         for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
  #|         return u8;
  #|       }
  #|       return p.v;
  #|     });
  #|   };
  #|   const stringifySafe = (obj) => JSON.stringify(obj, (_k, val) => (
  #|     typeof val === "bigint" ? { __ciallo_i64__: val.toString() } : val
  #|   ));
  #|   return (async () => {
  #|     try {
  #|       const args = decodeParams(paramsJson);
  #|       let stmt = db.prepare(sql);
  #|       if (args.length > 0) stmt = stmt.bind(...args);
  #|       const res = await stmt.all();
  #|       const rows = Array.isArray(res?.results) ? res.results : [];
  #|       return stringifySafe({ ok: true, results: rows });
  #|     } catch (e) {
  #|       return JSON.stringify({ ok: false, error: String(e?.message ?? e) });
  #|     }
  #|   })();
  #| }

///|
extern "js" fn js_d1_exec(
  db : D1Database,
  sql : String,
  params_json : String,
  use_bigint_i64 : Bool,
) -> @js_async.Promise[String] =
  #| (db, sql, paramsJson, useBigIntI64) => {
  #|   const decodeParams = (raw) => {
  #|     const arr = JSON.parse(raw);
  #|     return arr.map((p) => {
  #|       if (p === null || p.t === "null") return null;
  #|       if (p.t === "bool") return p.v ? 1 : 0;
  #|       if (p.t === "i32" || p.t === "f64") return p.v;
  #|       if (p.t === "i64") {
  #|         const bi = BigInt(p.v);
  #|         if (bi >= -9007199254740991n && bi <= 9007199254740991n) return Number(bi);
  #|         return useBigIntI64 ? bi : String(p.v);
  #|       }
  #|       if (p.t === "text" || p.t === "json") return p.v;
  #|       if (p.t === "bytes") {
  #|         const bin = atob(p.v);
  #|         const u8 = new Uint8Array(bin.length);
  #|         for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
  #|         return u8;
  #|       }
  #|       return p.v;
  #|     });
  #|   };
  #|   return (async () => {
  #|     try {
  #|       const args = decodeParams(paramsJson);
  #|       let stmt = db.prepare(sql);
  #|       if (args.length > 0) stmt = stmt.bind(...args);
  #|       const res = await stmt.run();
  #|       const changes = res?.meta?.changes ?? 0;
  #|       const lastRowId = res?.meta?.last_row_id ?? null;
  #|       return JSON.stringify({
  #|         ok: true,
  #|         changes: typeof changes === "bigint" ? changes.toString() : changes,
  #|         last_row_id: typeof lastRowId === "bigint" ? lastRowId.toString() : lastRowId,
  #|       });
  #|     } catch (e) {
  #|       return JSON.stringify({ ok: false, error: String(e?.message ?? e) });
  #|     }
  #|   })();
  #| }

///|
extern "js" fn js_d1_batch(
  db : D1Database,
  batch_json : String,
  use_bigint_i64 : Bool,
) -> @js_async.Promise[String] =
  #| (db, batchJson, useBigIntI64) => {
  #|   const decodeParams = (arr) => arr.map((p) => {
  #|     if (p === null || p.t === "null") return null;
  #|     if (p.t === "bool") return p.v ? 1 : 0;
  #|     if (p.t === "i32" || p.t === "f64") return p.v;
  #|     if (p.t === "i64") {
  #|       const bi = BigInt(p.v);
  #|       if (bi >= -9007199254740991n && bi <= 9007199254740991n) return Number(bi);
  #|       return useBigIntI64 ? bi : String(p.v);
  #|     }
  #|     if (p.t === "text" || p.t === "json") return p.v;
  #|     if (p.t === "bytes") {
  #|       const bin = atob(p.v);
  #|       const u8 = new Uint8Array(bin.length);
  #|       for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
  #|       return u8;
  #|     }
  #|     return p.v;
  #|   });
  #|   return (async () => {
  #|     try {
  #|       const items = JSON.parse(batchJson);
  #|       const stmts = items.map((item) => {
  #|         let stmt = db.prepare(item.sql);
  #|         const args = decodeParams(item.params);
  #|         if (args.length > 0) stmt = stmt.bind(...args);
  #|         return stmt;
  #|       });
  #|       if (typeof db.batch === "function") {
  #|         const results = await db.batch(stmts);
  #|         if (Array.isArray(results)) {
  #|           for (let i = 0; i < results.length; i++) {
  #|             const r = results[i];
  #|             if (r && r.success === false) {
  #|               return JSON.stringify({
  #|                 ok: false,
  #|                 error: String(r.error ?? ("D1 batch statement " + i + " failed")),
  #|               });
  #|             }
  #|           }
  #|         }
  #|       } else {
  #|         for (let i = 0; i < stmts.length; i++) {
  #|           const r = await stmts[i].run();
  #|           if (r && r.success === false) {
  #|             return JSON.stringify({
  #|               ok: false,
  #|               error: String(r.error ?? ("D1 batch statement " + i + " failed")),
  #|             });
  #|           }
  #|         }
  #|       }
  #|       return JSON.stringify({ ok: true });
  #|     } catch (e) {
  #|       return JSON.stringify({ ok: false, error: String(e?.message ?? e) });
  #|     }
  #|   })();
  #| }

///|
fn encode_params_array(params : Array[@orm_schema.SqlValue]) -> Json {
  let items : Array[Json] = []
  for p in params {
    let obj : Map[String, Json] = Map([])
    match p {
      @orm_schema.SqlValue::Null => obj["t"] = Json::string("null")
      @orm_schema.SqlValue::Bool(b) => {
        obj["t"] = Json::string("bool")
        obj["v"] = Json::boolean(b)
      }
      @orm_schema.SqlValue::Int32(n) => {
        obj["t"] = Json::string("i32")
        obj["v"] = Json::number(n.to_double())
      }
      @orm_schema.SqlValue::Int64(n) => {
        obj["t"] = Json::string("i64")
        obj["v"] = Json::string(n.to_string())
      }
      @orm_schema.SqlValue::Double(d) => {
        obj["t"] = Json::string("f64")
        obj["v"] = Json::number(d)
      }
      @orm_schema.SqlValue::Text(s) => {
        obj["t"] = Json::string("text")
        obj["v"] = Json::string(s)
      }
      @orm_schema.SqlValue::Bytes(b) => {
        obj["t"] = Json::string("bytes")
        obj["v"] = Json::string(@base64.encode(b))
      }
      @orm_schema.SqlValue::Json(j) => {
        obj["t"] = Json::string("json")
        obj["v"] = Json::string(j.stringify())
      }
    }
    items.push(Json::object(obj))
  }
  Json::array(items)
}

///|
fn encode_params_json(params : Array[@orm_schema.SqlValue]) -> String {
  encode_params_array(params).stringify()
}

///|
fn encode_batch_json(
  stmts : Array[(String, Array[@orm_schema.SqlValue])],
) -> String {
  let arr : Array[Json] = []
  for pair in stmts {
    let obj : Map[String, Json] = Map([])
    obj["sql"] = Json::string(pair.0)
    obj["params"] = encode_params_array(pair.1)
    arr.push(Json::object(obj))
  }
  Json::array(arr).stringify()
}

///|
fn map_d1_error(msg : String) -> @codec.DataError {
  if msg.contains("UNIQUE constraint failed") {
    @codec.DataError::UniqueViolation(constraint="d1_unique", detail=msg)
  } else if msg.contains("FOREIGN KEY constraint failed") {
    @codec.DataError::ForeignKeyViolation(constraint="d1_fk", detail=msg)
  } else {
    @codec.DataError::BackendError(code="D1_ERROR", message=msg)
  }
}

///|
fn json_to_sql_value(j : Json) -> @orm_schema.SqlValue {
  match j {
    Null => @orm_schema.SqlValue::Null
    True => @orm_schema.SqlValue::Bool(true)
    False => @orm_schema.SqlValue::Bool(false)
    Number(n, ..) =>
      if !(n.is_nan() || n.is_inf()) &&
        n >= -9007199254740991.0 &&
        n <= 9007199254740991.0 {
        let i = n.to_int64()
        if i.to_double() == n {
          @orm_schema.SqlValue::Int64(i)
        } else {
          @orm_schema.SqlValue::Double(n)
        }
      } else {
        @orm_schema.SqlValue::Double(n)
      }
    String(s) => @orm_schema.SqlValue::Text(s)
    Object(m) =>
      if m.length() == 1 {
        match m.get("__ciallo_i64__") {
          Some(String(raw)) =>
            match (Some(@string.parse_int64(raw)) catch { _ => None }) {
              Some(v) => @orm_schema.SqlValue::Int64(v)
              None => @orm_schema.SqlValue::Text(raw)
            }
          _ => @orm_schema.SqlValue::Json(j)
        }
      } else {
        @orm_schema.SqlValue::Json(j)
      }
    other => @orm_schema.SqlValue::Json(other)
  }
}

///|
fn parse_json_i64(j : Json) -> Int64? {
  match j {
    Number(n, ..) =>
      if !(n.is_nan() || n.is_inf()) &&
        n >= -9007199254740991.0 &&
        n <= 9007199254740991.0 {
        Some(n.to_int64())
      } else {
        None
      }
    String(s) => Some(@string.parse_int64(s)) catch { _ => None }
    _ => None
  }
}

///|
/// Cloudflare D1 无状态异步 SQL 驱动(--target js 专用,零连接池开销;事务走原子 d1.batch() 缓冲提交,杜绝 D1 BEGIN 报错)
pub struct D1Driver {
  priv db : D1Database
  priv use_bigint_for_large_i64 : Bool
}

///|
pub fn D1Driver::D1Driver(
  db : D1Database,
  use_bigint_for_large_i64~ : Bool = false,
) -> D1Driver {
  { db, use_bigint_for_large_i64, }
}

///|
async fn D1Driver::run_query(
  self : D1Driver,
  sql : String,
  params : Array[@orm_schema.SqlValue],
) -> Array[@orm_schema.SqlRow] raise @codec.DataError {
  let raw = js_d1_query(
    self.db,
    sql,
    encode_params_json(params),
    self.use_bigint_for_large_i64,
  ).wait() catch {
    err =>
      raise @codec.DataError::ConnectionFailed("D1 promise rejected: \{err}")
  }
  let parsed = @json.parse(raw) catch {
    err =>
      raise @codec.DataError::ProtocolError("invalid D1 JSON response: \{err}")
  }
  match parsed {
    Object(map) => {
      if map.get("ok") != Some(Json::boolean(true)) {
        let msg = match map.get("error") {
          Some(String(s)) => s
          _ => "unknown D1 query error"
        }
        raise map_d1_error(msg)
      }
      let out : Array[@orm_schema.SqlRow] = []
      let mut shared_index : @orm_schema.ColumnIndex? = None
      match map.get("results") {
        Some(Array(rows)) =>
          for r in rows {
            match r {
              Object(rmap) =>
                match shared_index {
                  None => {
                    let cols : Array[String] = []
                    let vals : Array[@orm_schema.SqlValue] = []
                    rmap.each((k, v) => {
                      cols.push(k)
                      vals.push(json_to_sql_value(v))
                    })
                    let ci = @orm_schema.ColumnIndex::ColumnIndex(cols)
                    shared_index = Some(ci)
                    out.push(@orm_schema.SqlRow::with_index(ci, vals))
                  }
                  Some(ci) => {
                    let cols = ci.columns()
                    if rmap.length() == cols.length() {
                      let vals : Array[@orm_schema.SqlValue] = Array(
                        capacity=cols.length(),
                      )
                      let mut all_matched = true
                      for col in cols {
                        match rmap.get(col) {
                          Some(v) => vals.push(json_to_sql_value(v))
                          None => {
                            all_matched = false
                            break
                          }
                        }
                      }
                      if all_matched {
                        out.push(@orm_schema.SqlRow::with_index(ci, vals))
                      } else {
                        let fallback_cols : Array[String] = []
                        let fallback_vals : Array[@orm_schema.SqlValue] = []
                        rmap.each((k, v) => {
                          fallback_cols.push(k)
                          fallback_vals.push(json_to_sql_value(v))
                        })
                        out.push(
                          @orm_schema.SqlRow::SqlRow(
                            columns=fallback_cols,
                            values=fallback_vals,
                          ),
                        )
                      }
                    } else {
                      let fallback_cols : Array[String] = []
                      let fallback_vals : Array[@orm_schema.SqlValue] = []
                      rmap.each((k, v) => {
                        fallback_cols.push(k)
                        fallback_vals.push(json_to_sql_value(v))
                      })
                      out.push(
                        @orm_schema.SqlRow::SqlRow(
                          columns=fallback_cols,
                          values=fallback_vals,
                        ),
                      )
                    }
                  }
                }
              _ => ()
            }
          }
        _ => ()
      }
      out
    }
    _ => raise @codec.DataError::ProtocolError("expected JSON object from D1")
  }
}

///|
async fn D1Driver::run_exec(
  self : D1Driver,
  sql : String,
  params : Array[@orm_schema.SqlValue],
) -> @driver.ExecResult raise @codec.DataError {
  let raw = js_d1_exec(
    self.db,
    sql,
    encode_params_json(params),
    self.use_bigint_for_large_i64,
  ).wait() catch {
    err =>
      raise @codec.DataError::ConnectionFailed("D1 promise rejected: \{err}")
  }
  let parsed = @json.parse(raw) catch {
    err =>
      raise @codec.DataError::ProtocolError("invalid D1 JSON response: \{err}")
  }
  match parsed {
    Object(map) => {
      if map.get("ok") != Some(Json::boolean(true)) {
        let msg = match map.get("error") {
          Some(String(s)) => s
          _ => "unknown D1 exec error"
        }
        raise map_d1_error(msg)
      }
      let changes : Int64 = match map.get("changes") {
        Some(v) => parse_json_i64(v).unwrap_or(0L)
        None => 0L
      }
      let last_id : Int64? = match map.get("last_row_id") {
        Some(v) => parse_json_i64(v)
        None => None
      }
      @driver.ExecResult::ExecResult(
        rows_affected=changes,
        last_insert_id?=last_id,
      )
    }
    _ => raise @codec.DataError::ProtocolError("expected JSON object from D1")
  }
}

///|
async fn D1Driver::run_batch(
  self : D1Driver,
  stmts : Array[(String, Array[@orm_schema.SqlValue])],
) -> Unit raise @codec.DataError {
  if stmts.is_empty() {
    return
  }
  let raw = js_d1_batch(
    self.db,
    encode_batch_json(stmts),
    self.use_bigint_for_large_i64,
  ).wait() catch {
    err => raise @codec.DataError::ConnectionFailed("D1 batch rejected: \{err}")
  }
  let parsed = @json.parse(raw) catch {
    err =>
      raise @codec.DataError::ProtocolError(
        "invalid D1 batch JSON response: \{err}",
      )
  }
  match parsed {
    Object(map) =>
      if map.get("ok") != Some(Json::boolean(true)) {
        let msg = match map.get("error") {
          Some(String(s)) => s
          _ => "unknown D1 batch error"
        }
        raise map_d1_error(msg)
      }
    _ => raise @codec.DataError::ProtocolError("expected JSON object from D1")
  }
}

///|
/// Cloudflare D1 Buffered Batch Transaction(收集写语句在 commit 时一次性原子执行 d1.batch(),严禁发送 BEGIN)
priv struct D1Tx {
  driver : D1Driver
  mut closed : Bool
  staged : Array[(String, Array[@orm_schema.SqlValue])]
  savepoints : Array[(String, Int32)]
}

///|
impl @driver.SqlTx for D1Tx with fn dialect(_self) -> @dialect.DialectKind {
  @dialect.DialectKind::Sqlite
}

///|
impl @driver.SqlTx for D1Tx with fn is_buffered_batch(_self) -> Bool {
  true
}

///|
impl @driver.SqlTx for D1Tx with fn query_rows(self, sql, params) -> Array[
  @orm_schema.SqlRow,
] raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  if !self.staged.is_empty() {
    raise @codec.DataError::BackendError(
      code="D1_INTERACTIVE_TX_UNSUPPORTED",
      message="Cloudflare D1 does not support interactive reads after uncommitted writes in a transaction; use an atomic write batch or Durable Object SQLite",
    )
  }
  self.driver.run_query(sql, params)
}

///|
impl @driver.SqlTx for D1Tx with fn execute(self, sql, params) -> @driver.ExecResult raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  self.staged.push((sql, params.copy()))
  @driver.ExecResult::ExecResult(rows_affected=0L)
}

///|
impl @driver.SqlTx for D1Tx with fn savepoint(self, name) -> Unit raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  self.savepoints.push((name, self.staged.length()))
}

///|
impl @driver.SqlTx for D1Tx with fn release_savepoint(self, name) -> Unit raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  let mut idx = self.savepoints.length() - 1
  while idx >= 0 {
    if self.savepoints[idx].0 == name {
      while self.savepoints.length() > idx {
        ignore(self.savepoints.pop())
      }
      return
    }
    idx -= 1
  }
}

///|
impl @driver.SqlTx for D1Tx with fn rollback_to_savepoint(self, name) -> Unit raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  let mut idx = self.savepoints.length() - 1
  while idx >= 0 {
    if self.savepoints[idx].0 == name {
      let watermark = self.savepoints[idx].1
      while self.staged.length() > watermark {
        ignore(self.staged.pop())
      }
      while self.savepoints.length() > idx {
        ignore(self.savepoints.pop())
      }
      return
    }
    idx -= 1
  }
}

///|
impl @driver.SqlTx for D1Tx with fn commit(self) -> Unit raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  self.closed = true
  let batch = self.staged.copy()
  self.staged.clear()
  self.savepoints.clear()
  self.driver.run_batch(batch)
}

///|
impl @driver.SqlTx for D1Tx with fn rollback(self) -> Unit raise @codec.DataError {
  if self.closed {
    return
  }
  self.closed = true
  self.staged.clear()
  self.savepoints.clear()
}

///|
pub impl @driver.SqlDriver for D1Driver with fn dialect(_self) -> @dialect.DialectKind {
  @dialect.DialectKind::Sqlite
}

///|
pub impl @driver.SqlDriver for D1Driver with fn query_rows(self, sql, params) -> Array[
  @orm_schema.SqlRow,
] raise @codec.DataError {
  self.run_query(sql, params)
}

///|
pub impl @driver.SqlDriver for D1Driver with fn execute(self, sql, params) -> @driver.ExecResult raise @codec.DataError {
  self.run_exec(sql, params)
}

///|
pub impl @driver.SqlDriver for D1Driver with fn begin_tx(self) -> &@driver.SqlTx raise @codec.DataError {
  let tx : D1Tx = { driver: self, closed: false, staged: [], savepoints: [], }
  tx as &@driver.SqlTx
}