-- ─── GoClaw Phase 21: Real Docker Swarm Management ────────────────────────────

-- swarmNodes: persistent record of each node in the swarm
-- Stores the advertise address, join tokens, role, labels,
-- and custom domain/port mapping so the UI can show connection info.
CREATE TABLE IF NOT EXISTS `swarmNodes` (
  `id`            INT AUTO_INCREMENT PRIMARY KEY,
  `nodeId`        VARCHAR(64)  NOT NULL UNIQUE,          -- Docker node ID
  `hostname`      VARCHAR(128) NOT NULL,
  `role`          ENUM('manager','worker') NOT NULL DEFAULT 'worker',
  `state`         ENUM('ready','down','disconnected') NOT NULL DEFAULT 'ready',
  `availability`  ENUM('active','pause','drain') NOT NULL DEFAULT 'active',
  `advertiseAddr` VARCHAR(128),                          -- IP:port used by swarm
  `domain`        VARCHAR(256),                          -- optional custom domain
  `sshPort`       INT DEFAULT 22,
  `labels`        JSON,
  `engineVersion` VARCHAR(64),
  `cpuCores`      INT DEFAULT 0,
  `memTotalMB`    BIGINT DEFAULT 0,
  `isManager`     TINYINT(1) DEFAULT 0,
  `isLeader`      TINYINT(1) DEFAULT 0,
  `lastSeenAt`    TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `createdAt`     TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX `swarmNodes_role_idx` (`role`),
  INDEX `swarmNodes_state_idx` (`state`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- swarmTokens: stores join tokens (manager + worker) for the swarm
-- Only one row (the current swarm). Updated by the Go gateway on startup.
CREATE TABLE IF NOT EXISTS `swarmTokens` (
  `id`           INT AUTO_INCREMENT PRIMARY KEY,
  `managerToken` TEXT,
  `workerToken`  TEXT,
  `managerAddr`  VARCHAR(128),          -- IP:2377 to join as manager/worker
  `updatedAt`    TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Add serviceId + replicas columns to agents so each agent maps to a swarm service
ALTER TABLE `agents`
  ADD COLUMN IF NOT EXISTS `serviceId`   VARCHAR(128) DEFAULT NULL COMMENT 'Docker Swarm service ID',
  ADD COLUMN IF NOT EXISTS `serviceName` VARCHAR(128) DEFAULT NULL COMMENT 'Docker Swarm service name',
  ADD COLUMN IF NOT EXISTS `replicas`    INT DEFAULT 1              COMMENT 'Desired replica count';
