///|
/// Full-stack Trait integrations for `Uuid`, `Ulid`, and `Snowflake`:
/// - `@json.ToJson` & `@json.FromJson` (`Uuid`/`Ulid` as canonical strings; `Snowflake` as `Int64String`)
/// - `@ciallo_schema.Schema` & `@ciallo_schema.FromParam` (`ctx.param_as("id") : Uuid`)
/// - `@orm_schema.ToSqlValue` & `@orm_schema.FromSqlValue`

///|
pub impl ToJson for Uuid with fn to_json(self) -> Json {
  Json::string(self.to_string())
}

///|
pub extend Uuid with ToJson::{to_json}

///|
pub impl @json.FromJson for Uuid with fn from_json(json, path) -> Uuid raise @json.JsonDecodeError {
  match json {
    String(s) =>
      Uuid::parse(s) catch {
        err => raise @json.JsonDecodeError((path, "invalid UUID: \{Repr(err)}"))
      }
    _ => raise @json.JsonDecodeError((path, "expected UUID string"))
  }
}

///|
pub impl @ciallo_schema.Schema for Uuid with fn schema_node(_proxy) -> @ciallo_schema.SchemaNode {
  @ciallo_schema.SchemaNode::string(
    min_len=36,
    max_len=36,
    meta=@ciallo_schema.SchemaMeta::SchemaMeta(format="uuid"),
  )
}

///|
pub impl @ciallo_schema.FromParam for Uuid with fn from_param(name, raw) -> Uuid raise @ciallo_schema.ValidationError {
  Uuid::parse(raw) catch {
    _ =>
      raise @ciallo_schema.ValidationError::InvalidInput(issues=[
        {
          path: "/\{name}",
          message: "invalid UUID path parameter '\{raw}'",
          expected: "uuid",
        },
      ])
  }
}

///|
pub impl @orm_schema.ToSqlValue for Uuid with fn to_sql_value(self) -> @orm_schema.SqlValue {
  @orm_schema.SqlValue::Text(self.to_string())
}

///|
pub impl @orm_schema.FromSqlValue for Uuid with fn from_sql_value(val) -> Uuid raise @codec.DataError {
  match val {
    @orm_schema.SqlValue::Text(s) =>
      Uuid::parse(s) catch {
        err =>
          raise @codec.DataError::DecodeFailed(
            field="uuid",
            message="invalid UUID text: \{Repr(err)}",
          )
      }
    @orm_schema.SqlValue::Bytes(b) =>
      Uuid::from_bytes(b) catch {
        err =>
          raise @codec.DataError::DecodeFailed(
            field="uuid",
            message="invalid UUID bytes: \{Repr(err)}",
          )
      }
    _ =>
      raise @codec.DataError::DecodeFailed(
        field="uuid",
        message="expected TEXT or BYTES for Uuid",
      )
  }
}

///|
pub impl ToJson for Ulid with fn to_json(self) -> Json {
  Json::string(self.to_string())
}

///|
pub extend Ulid with ToJson::{to_json}

///|
pub impl @json.FromJson for Ulid with fn from_json(json, path) -> Ulid raise @json.JsonDecodeError {
  match json {
    String(s) =>
      Ulid::parse(s) catch {
        err => raise @json.JsonDecodeError((path, "invalid ULID: \{Repr(err)}"))
      }
    _ => raise @json.JsonDecodeError((path, "expected ULID string"))
  }
}

///|
pub impl @ciallo_schema.Schema for Ulid with fn schema_node(_proxy) -> @ciallo_schema.SchemaNode {
  @ciallo_schema.SchemaNode::string(
    min_len=26,
    max_len=26,
    meta=@ciallo_schema.SchemaMeta::SchemaMeta(format="ulid"),
  )
}

///|
pub impl @ciallo_schema.FromParam for Ulid with fn from_param(name, raw) -> Ulid raise @ciallo_schema.ValidationError {
  Ulid::parse(raw) catch {
    _ =>
      raise @ciallo_schema.ValidationError::InvalidInput(issues=[
        {
          path: "/\{name}",
          message: "invalid ULID path parameter '\{raw}'",
          expected: "ulid",
        },
      ])
  }
}

///|
pub impl @orm_schema.ToSqlValue for Ulid with fn to_sql_value(self) -> @orm_schema.SqlValue {
  @orm_schema.SqlValue::Text(self.to_string())
}

///|
pub impl @orm_schema.FromSqlValue for Ulid with fn from_sql_value(val) -> Ulid raise @codec.DataError {
  match val {
    @orm_schema.SqlValue::Text(s) =>
      Ulid::parse(s) catch {
        err =>
          raise @codec.DataError::DecodeFailed(
            field="ulid",
            message="invalid ULID text: \{Repr(err)}",
          )
      }
    _ =>
      raise @codec.DataError::DecodeFailed(
        field="ulid",
        message="expected TEXT for Ulid",
      )
  }
}

///|
/// Serializes `Snowflake` as a decimal `Int64String` to preserve full 64-bit precision in JS/TS frontends.
pub impl ToJson for Snowflake with fn to_json(self) -> Json {
  Json::string(self.0.to_string())
}

///|
pub extend Snowflake with ToJson::{to_json}

///|
pub impl @json.FromJson for Snowflake with fn from_json(json, path) -> Snowflake raise @json.JsonDecodeError {
  match json {
    String(s) => {
      let n = @string.parse_int64(s) catch {
        _ =>
          raise @json.JsonDecodeError(
            (path, "invalid Snowflake Int64String '\{s}'"),
          )
      }
      if n < 0L {
        raise @json.JsonDecodeError(
          (path, "Snowflake must be non-negative: '\{s}'"),
        )
      }
      Snowflake(n)
    }
    Number(d, ..) =>
      if !(d.is_nan() || d.is_inf()) && d >= 0.0 && d <= 9007199254740991.0 {
        let i = d.to_int64()
        if i.to_double() == d {
          Snowflake(i)
        } else {
          raise @json.JsonDecodeError((path, "Snowflake must be an integer"))
        }
      } else if d < 0.0 {
        raise @json.JsonDecodeError((path, "Snowflake must be non-negative"))
      } else {
        raise @json.JsonDecodeError(
          (path, "Snowflake > 2^53-1 must be encoded as decimal string"),
        )
      }
    _ =>
      raise @json.JsonDecodeError((path, "expected Snowflake decimal string"))
  }
}

///|
pub impl @ciallo_schema.Schema for Snowflake with fn schema_node(_proxy) -> @ciallo_schema.SchemaNode {
  @ciallo_schema.SchemaNode::int64_string(
    min=0L,
    meta=@ciallo_schema.SchemaMeta::SchemaMeta(format="int64"),
  )
}

///|
pub impl @ciallo_schema.FromParam for Snowflake with fn from_param(name, raw) -> Snowflake raise @ciallo_schema.ValidationError {
  let n = @string.parse_int64(raw) catch {
    _ =>
      raise @ciallo_schema.ValidationError::InvalidInput(issues=[
        {
          path: "/\{name}",
          message: "invalid Snowflake path parameter '\{raw}'",
          expected: "int64",
        },
      ])
  }
  if n < 0L {
    raise @ciallo_schema.ValidationError::InvalidInput(issues=[
      {
        path: "/\{name}",
        message: "Snowflake path parameter '\{raw}' must be non-negative",
        expected: "non-negative int64",
      },
    ])
  }
  Snowflake(n)
}

///|
pub impl @orm_schema.ToSqlValue for Snowflake with fn to_sql_value(self) -> @orm_schema.SqlValue {
  @orm_schema.SqlValue::Int64(self.0)
}

///|
pub impl @orm_schema.FromSqlValue for Snowflake with fn from_sql_value(val) -> Snowflake raise @codec.DataError {
  match val {
    @orm_schema.SqlValue::Int64(n) => Snowflake(n)
    @orm_schema.SqlValue::Int32(n) => Snowflake(n.to_int64())
    @orm_schema.SqlValue::Text(s) => {
      let n = @string.parse_int64(s) catch {
        _ =>
          raise @codec.DataError::DecodeFailed(
            field="snowflake",
            message="invalid Snowflake SQL text '\{s}'",
          )
      }
      Snowflake(n)
    }
    _ =>
      raise @codec.DataError::DecodeFailed(
        field="snowflake",
        message="expected Int64 or Text for Snowflake",
      )
  }
}