CREATE TABLE IF NOT EXISTS chat_conversations (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_id BIGINT UNSIGNED NOT NULL,
  type VARCHAR(32) NOT NULL DEFAULT 'order_group',
  title VARCHAR(128) NOT NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'active',
  last_message_id BIGINT UNSIGNED NULL,
  last_message_preview VARCHAR(255) NOT NULL DEFAULT '',
  last_message_at DATETIME NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_chat_conversations_order_id (order_id),
  KEY idx_chat_conversations_last_message_at (last_message_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS chat_participants (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  conversation_id BIGINT UNSIGNED NOT NULL,
  participant_type VARCHAR(16) NOT NULL,
  participant_id BIGINT UNSIGNED NOT NULL,
  role VARCHAR(32) NOT NULL,
  last_read_at DATETIME NULL,
  joined_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_chat_participants_member (conversation_id, participant_type, participant_id),
  KEY idx_chat_participants_participant (participant_type, participant_id),
  KEY idx_chat_participants_conversation (conversation_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS chat_messages (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  conversation_id BIGINT UNSIGNED NOT NULL,
  sender_type VARCHAR(16) NOT NULL,
  sender_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
  sender_role VARCHAR(32) NOT NULL DEFAULT '',
  content_type VARCHAR(32) NOT NULL DEFAULT 'text',
  content TEXT NULL,
  attachment_urls JSON NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_chat_messages_conversation_id (conversation_id, id),
  KEY idx_chat_messages_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO system_configs (`key`, `value`, description)
VALUES ('chat.default_support_admin_id', '1', '订单群聊默认接入的客服管理员 ID')
ON DUPLICATE KEY UPDATE description = VALUES(description);
