CREATE TABLE IF NOT EXISTS dns_credentials ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, scope_key VARCHAR(64) NOT NULL, tenant_id BIGINT UNSIGNED NULL, secret_ref CHAR(32) NOT NULL UNIQUE, label VARCHAR(80) NOT NULL, provider ENUM('cloudflare','aliyun','tencent') NOT NULL, zone_name VARCHAR(253) NOT NULL, credential_ciphertext VARBINARY(4096) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, CONSTRAINT fk_dns_credentials_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE, UNIQUE KEY uk_dns_credentials_scope_zone (scope_key, zone_name), INDEX idx_dns_credentials_tenant (tenant_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS system_secrets ( secret_key VARCHAR(80) PRIMARY KEY, secret_ciphertext VARBINARY(4096) NOT NULL, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS certificate_automations ( site_id BIGINT UNSIGNED PRIMARY KEY, mode ENUM('off','manual','http-01','dns-01') NOT NULL DEFAULT 'off', expires_at DATETIME NULL, last_attempt_at DATETIME NULL, next_attempt_at DATETIME NULL, last_error VARCHAR(500) NULL, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, CONSTRAINT fk_certificate_automations_site FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE, INDEX idx_certificate_automations_due (mode, next_attempt_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; INSERT INTO certificate_automations(site_id,mode) SELECT id,IF(auto_ssl,'http-01',IF(ssl_status='active','manual','off')) FROM sites ON DUPLICATE KEY UPDATE site_id=VALUES(site_id);