--- vk

ALTER TABLE vk_channels
  ADD uuid VARCHAR(36),
  ADD name VARCHAR(1024),
  ADD deleted_at TIMESTAMPTZ,
  ADD restored_at TIMESTAMPTZ,
  DROP COLUMN last_sent_message_id,
  DROP COLUMN secret;

ALTER TABLE vk_channels
  ALTER COLUMN group_id DROP NOT NULL,
  ALTER COLUMN access_token DROP NOT NULL,
  ALTER COLUMN confirmation_code DROP NOT NULL;

DROP INDEX vk_channels_access_token_uniq;
DROP INDEX vk_channels_group_id_uniq;

CREATE UNIQUE INDEX vk_channels_uuid_uniq
  ON vk_channels (uuid)
  WHERE uuid IS NOT NULL;

CREATE UNIQUE INDEX vk_channels_group_id_uniq
  ON vk_channels (group_id)
  WHERE deleted = FALSE AND group_id IS NOT NULL;

-- vk-users

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

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

ALTER TABLE vk_users
  ALTER COLUMN created_at DROP NOT NULL,
  ALTER COLUMN updated_at DROP NOT NULL;

-- vk-chats

CREATE TABLE vk_chats (
  id         BIGINT PRIMARY KEY,
  chat_id    BIGINT      NOT NULL REFERENCES chats (id),
  user_id    BIGINT      NOT NULL REFERENCES vk_users (id),
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);

CREATE SEQUENCE vk_chats_id_seq;

CREATE UNIQUE INDEX vk_chats_chat_uniq
  ON vk_chats (chat_id);

-- vk-messages

DROP TABLE vk_messages;
