SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE DATABASE IF NOT EXISTS hyapp_activity DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_activity;

CREATE TABLE IF NOT EXISTS activities (
  activity_id VARCHAR(96) NOT NULL PRIMARY KEY,
  status VARCHAR(32) NOT NULL,
  updated_at_ms BIGINT NOT NULL,
  KEY idx_activities_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS activity_event_consumption (
  event_id VARCHAR(96) NOT NULL PRIMARY KEY,
  event_type VARCHAR(96) NOT NULL,
  source VARCHAR(64) NOT NULL,
  status VARCHAR(32) NOT NULL,
  failure_reason VARCHAR(255) NULL,
  consumed_at_ms BIGINT NULL,
  created_at_ms BIGINT NOT NULL,
  updated_at_ms BIGINT NOT NULL,
  KEY idx_activity_event_consumption_status (status),
  KEY idx_activity_event_consumption_updated_at (updated_at_ms)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS activity_outbox (
  outbox_id VARCHAR(96) NOT NULL PRIMARY KEY,
  event_type VARCHAR(96) NOT NULL,
  payload BLOB NOT NULL,
  status VARCHAR(32) NOT NULL,
  retry_count INT NOT NULL DEFAULT 0,
  next_retry_at_ms BIGINT NOT NULL,
  created_at_ms BIGINT NOT NULL,
  updated_at_ms BIGINT NOT NULL,
  KEY idx_activity_outbox_status_retry (status, next_retry_at_ms)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
