-- 弹性节点基建。附加式变更。
ALTER TABLE nodes ADD COLUMN provider_instance_id TEXT NULL;
ALTER TABLE nodes ADD COLUMN elastic_ip_id        TEXT NULL;

-- node_events.event 的 'ip_rotated' 已在 SQLite 基线（000006）预置，无需扩展。

CREATE TABLE provision_idempotency (
  idempotency_key TEXT NOT NULL PRIMARY KEY,
  node_uuid       TEXT NOT NULL,
  created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE replacements (
  uuid        TEXT NOT NULL PRIMARY KEY,
  old_node_id INTEGER NOT NULL,
  new_node_id INTEGER NULL,
  pool        TEXT NOT NULL CHECK (pool IN ('consumable','premium')),
  status      TEXT NOT NULL DEFAULT 'running' CHECK (status IN ('running','done','failed')),
  step        TEXT NOT NULL DEFAULT 'open_new',
  detail      TEXT NULL,                           -- JSON
  created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_repl_status   ON replacements (status);
CREATE INDEX idx_repl_old_node ON replacements (old_node_id);

-- 等价 MySQL 的 ON UPDATE CURRENT_TIMESTAMP（recursive_triggers 默认关，不会自递归）。
CREATE TRIGGER trg_replacements_updated_at
AFTER UPDATE ON replacements
FOR EACH ROW
BEGIN
  UPDATE replacements SET updated_at = CURRENT_TIMESTAMP WHERE uuid = NEW.uuid;
END;
