-- Phase 3 of the Projects/Tasks governance upgrade: outbound webhooks. A subscription
-- receives an HMAC-SHA256-signed POST for the event types it's subscribed to (workitem
-- status changes today; more event types can be added without a schema change).
-- Idempotent (information_schema-guarded), additive only.
-- Deploy: mysql -u root -p db_abos_v0.1 < db/webhook_subscriptions.sql

USE db_abos_v0.1;

CREATE TABLE IF NOT EXISTS dim_webhook_subscriptions (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    tenant_id INT NOT NULL,
    name VARCHAR(255) NOT NULL,
    target_url VARCHAR(1000) NOT NULL,
    secret VARCHAR(255) NOT NULL COMMENT 'HMAC-SHA256 signing key — never returned by the API after creation',
    event_types VARCHAR(500) NOT NULL COMMENT 'CSV, e.g. "workitem.status_changed,workitem.created"',
    is_enabled TINYINT(1) NOT NULL DEFAULT 1,
    created_at TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6),
    created_by INT NULL,
    updated_at TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
    updated_by INT NULL,
    is_deleted TINYINT(1) NOT NULL DEFAULT 0,
    INDEX idx_webhook_subscriptions_tenant (tenant_id, is_deleted, is_enabled)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Auditable delivery log — one row per delivery attempt, so retries/backoff are inspectable.
CREATE TABLE IF NOT EXISTS fact_webhook_deliveries (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    tenant_id INT NOT NULL,
    subscription_id BIGINT NOT NULL,
    event_type VARCHAR(128) NOT NULL,
    attempt INT NOT NULL DEFAULT 1,
    response_status INT NULL,
    success TINYINT(1) NOT NULL DEFAULT 0,
    error_message VARCHAR(1000) NULL,
    created_at TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6),
    INDEX idx_webhook_deliveries_subscription (tenant_id, subscription_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
