-- Internal chat between users of the same business account: one-to-one and group conversations.
-- Safe to run more than once. Run it BEFORE deploying the build that uses these tables.

CREATE TABLE IF NOT EXISTS fact_chat_conversation (
  id               BIGINT       NOT NULL AUTO_INCREMENT,
  tenant_id        INT          NOT NULL,
  type             VARCHAR(10)  NOT NULL,              -- DIRECT or GROUP
  title            VARCHAR(150) NULL,                  -- groups only
  direct_key       VARCHAR(64)  NULL,                  -- DIRECT only: "lowerUserId:higherUserId", one conversation per pair
  created_by       INT          NOT NULL,
  created_at       DATETIME(6)  NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  last_message_at  DATETIME(6)  NULL,
  is_deleted       TINYINT(1)   NOT NULL DEFAULT 0,
  PRIMARY KEY (id),
  UNIQUE KEY uq_chat_direct (tenant_id, direct_key),
  KEY idx_chat_conversation_tenant (tenant_id, last_message_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS fact_chat_participant (
  id                    BIGINT      NOT NULL AUTO_INCREMENT,
  conversation_id       BIGINT      NOT NULL,
  tenant_id             INT         NOT NULL,
  user_id               INT         NOT NULL,
  role                  VARCHAR(10) NOT NULL DEFAULT 'MEMBER',   -- ADMIN or MEMBER
  last_read_message_id  BIGINT      NULL,
  joined_at             DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  left_at               DATETIME(6) NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_chat_participant (conversation_id, user_id),
  KEY idx_chat_participant_user (tenant_id, user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS fact_chat_message (
  id               BIGINT      NOT NULL AUTO_INCREMENT,
  conversation_id  BIGINT      NOT NULL,
  tenant_id        INT         NOT NULL,
  sender_user_id   INT         NOT NULL,
  body             TEXT        NOT NULL,
  refs_json        TEXT        NULL,                -- items the message tags (type, id, label, url), as JSON
  reply_to_id      BIGINT      NULL,
  created_at       DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  edited_at        DATETIME(6) NULL,
  is_deleted       TINYINT(1)  NOT NULL DEFAULT 0,
  PRIMARY KEY (id),
  KEY idx_chat_message_conversation (conversation_id, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
