CREATE TABLE IF NOT EXISTS platform_billing_overrides (
    id INT AUTO_INCREMENT PRIMARY KEY,
    tenant_id INT NOT NULL UNIQUE,
    override_mode VARCHAR(80) NOT NULL,
    override_amount DECIMAL(12,2) NULL,
    override_reason TEXT NULL,
    updated_by VARCHAR(190) NOT NULL,
    updated_at DATETIME NOT NULL
);

SET @billing_event_index_exists := (
    SELECT COUNT(1)
    FROM INFORMATION_SCHEMA.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'billing_events'
      AND INDEX_NAME = 'billing_events_provider_event_unique'
);

SET @billing_event_index_sql := IF(
    @billing_event_index_exists = 0,
    'ALTER TABLE billing_events ADD UNIQUE KEY billing_events_provider_event_unique (provider, provider_event_id)',
    'SELECT 1'
);

PREPARE billing_event_index_statement FROM @billing_event_index_sql;
EXECUTE billing_event_index_statement;
DEALLOCATE PREPARE billing_event_index_statement;
