--- telegram

ALTER TABLE telegram_channels
  ADD uuid VARCHAR(36),
  ADD user_id BIGINT,
  ADD user_name VARCHAR(1024),
  ADD deleted_at TIMESTAMPTZ,
  ADD restored_at TIMESTAMPTZ,
  DROP COLUMN last_sent_message_id;

ALTER TABLE telegram_channels
  ALTER COLUMN bot_token DROP NOT NULL;

CREATE UNIQUE INDEX telegram_channels_uuid_uniq
  ON telegram_channels (uuid)
  WHERE uuid IS NOT NULL;

CREATE UNIQUE INDEX telegram_channel_nondeleted_user_id_uniq
  ON telegram_channels (user_id)
  WHERE user_id IS NOT NULL AND deleted = FALSE;

-- telegram-users

ALTER TABLE telegram_users
  DROP COLUMN client_id,
  ADD created_at TIMESTAMPTZ,
  ADD updated_at TIMESTAMPTZ;

UPDATE telegram_users
SET
  created_at = now(),
  updated_at = now();

ALTER TABLE telegram_users
  ALTER COLUMN created_at SET NOT NULL,
  ALTER COLUMN updated_at SET NOT NULL;

-- telegram-chats

CREATE TABLE telegram_chats (
  id               BIGINT PRIMARY KEY,
  chat_id          BIGINT      NOT NULL REFERENCES chats (id),
  telegram_chat_id BIGINT      NOT NULL,
  created_at       TIMESTAMPTZ NOT NULL,
  updated_at       TIMESTAMPTZ NOT NULL
);

CREATE SEQUENCE telegram_chats_id_seq;

CREATE UNIQUE INDEX telegram_chats_chat_uniq
  ON telegram_chats (chat_id);

-- telegram-messages

DROP TABLE telegram_messages;
