\ir ./begin.sql

SELECT expect(
  $$ SELECT snowflake_gen() & ((1 << 14) - 1) $$,
  '42',
  'snowflake_gen() seq initial'
) \gset

SELECT expect(
  $$ SELECT snowflake_gen() & ((1 << 14) - 1) $$,
  '43',
  'snowflake_gen() seq next'
) \gset

SELECT expect(
  $$ SELECT abs(
    (snowflake_gen() >> (14 + 10 + 5) << 5)
    + $$ || :'CONST_SNOWFLAKE_TS_START' || $$
    - 1000 * EXTRACT(EPOCH FROM clock_timestamp())
  ) < 10000 $$,
  'true',
  'snowflake_gen() highest ts bits'
) \gset

SELECT expect(
  $$ SELECT (snowflake_gen() >> (10 + 14)) & ((1 << 5) - 1) $$,
  '1',
  'snowflake_gen() cluster_no'
) \gset

SELECT expect(
  $$ SELECT (snowflake_gen() >> 14) & ((1 << 10) - 1) $$,
  '123',
  'snowflake_gen() island_no'
) \gset

SELECT expect(
  $$ SELECT (snowflake_gen(cluster_no_bits:=0, ts_bits:=40) >> 14) & ((1 << 10) - 1) $$,
  '123',
  'snowflake_gen() no cluster bits'
) \gset

SELECT expect(
  $$ SELECT abs(
    (snowflake_gen(cluster_no_bits:=0, ts_bits:=40) >> (14 + 10))
    + $$ || :'CONST_SNOWFLAKE_TS_START' || $$
    - 1000 * EXTRACT(EPOCH FROM clock_timestamp())
  ) < 10000 $$,
  'true',
  'snowflake_gen() full ts when no cluster bits'
) \gset


SELECT snowflake_gen() AS "snowflake_gen() sample result";

SELECT expect(
  $$ SELECT snowflake_gen('test_custom_seq') & ((1 << 14) - 1) $$,
  '1',
  'snowflake_gen(test_custom_seq)'
) \gset

SELECT expect_raise(
  $$SELECT snowflake_gen(ts_bits := 10, cluster_no_bits := 10, island_no_bits := 10, seq_bits := 10)$$,
  'ts_bits=10 + cluster_no_bits=10 + island_no_bits=10 + seq_bits=10 must be 64 exactly',
  'snowflake_gen()'
) \gset

\ir ./rollback.sql
