CREATE TABLE IF NOT EXISTS platform_notify_delivery_guard (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    channel_code VARCHAR(32) NOT NULL,
    receiver_ref VARCHAR(128) NOT NULL,
    stat_date DATE NOT NULL,
    daily_count INT NOT NULL DEFAULT 0,
    last_sent_at DATETIME DEFAULT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_platform_notify_delivery_guard (channel_code, receiver_ref, stat_date),
    KEY idx_platform_notify_delivery_guard_date (stat_date, channel_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS platform_notify_circuit_breaker (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    channel_code VARCHAR(32) NOT NULL,
    consecutive_failures INT NOT NULL DEFAULT 0,
    breaker_until DATETIME DEFAULT NULL,
    last_failure_message VARCHAR(500) DEFAULT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_platform_notify_circuit_breaker (channel_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO platform_notify_circuit_breaker (channel_code, consecutive_failures, breaker_until, last_failure_message)
SELECT 'EMAIL', 0, NULL, NULL
WHERE NOT EXISTS (
    SELECT 1 FROM platform_notify_circuit_breaker WHERE channel_code = 'EMAIL'
);

INSERT INTO platform_notify_circuit_breaker (channel_code, consecutive_failures, breaker_until, last_failure_message)
SELECT 'SMS', 0, NULL, NULL
WHERE NOT EXISTS (
    SELECT 1 FROM platform_notify_circuit_breaker WHERE channel_code = 'SMS'
);
