create table if not exists users (
  id uuid primary key not null default gen_random_uuid(),
  telegram_id bigint not null UNIQUE
);

create table if not exists currency (
  id serial primary key not null,
  symbol text not null UNIQUE
  -- decimals integer not null
);

create table if not exists instrument (
  id uuid primary key not null default gen_random_uuid(),
  base_currency_id integer references currency(id) not null,
  quoted_currency_id integer references currency(id) not null,
  CHECK (base_currency_id <> quoted_currency_id),
  UNIQUE (base_currency_id, quoted_currency_id)
);

create type alert_condition as enum ('above', 'below');

create table if not exists alert (
  id uuid primary key not null default gen_random_uuid(),
  user_id uuid references users(id) not null,
  instrument_id uuid references instrument(id) not null,
  price text not null,
  active bool not null default true,
  condition alert_condition not null
);

insert into currency(symbol) values ('USDT'), ('BTC'), ('ETH'), ('SOL');

insert into instrument (base_currency_id, quoted_currency_id) values
  ((select id from currency where symbol = 'BTC'), (select id from currency where symbol = 'USDT')),
  ((select id from currency where symbol = 'ETH'), (select id from currency where symbol = 'USDT')),
  ((select id from currency where symbol = 'SOL'), (select id from currency where symbol = 'USDT'));

create table if not exists alerter_state (
  last_alert_check timestamptz
);

-- single row; UPDATE always succeeds without upsert logic
insert into alerter_state(last_alert_check) values (null);
