-- RAW Bronze: one row per HTTP JSON page returned by UsageAggregates.
--
-- Migration recommendation:
--   1. rename/archive the current wide Bronze table;
--   2. create this table;
--   3. replay Bronze for the required business dates;
--   4. build azure_sponsorship_usage_silver from the new RAW Bronze.

CREATE TABLE IF NOT EXISTS azure_sponsorship_billing_bronze (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,

    provider_code VARCHAR(32) NOT NULL,
    source_system VARCHAR(100) NOT NULL,
    source_name VARCHAR(100) NOT NULL,

    scope_type VARCHAR(50) NULL,
    scope_id VARCHAR(128) NULL,

    business_date DATE NOT NULL,

    source_uri_logical VARCHAR(1000) NULL,
    request_url TEXT NULL,
    page_number INT NULL,
    source_record_number INT NULL,
    api_version VARCHAR(64) NULL,

    request_context LONGTEXT NULL,

    source_hash CHAR(64) NOT NULL,
    schema_hash CHAR(64) NULL,

    ingestion_run_id CHAR(36) NULL,
    ingestion_time DATETIME(6) NOT NULL,

    payload LONGTEXT NOT NULL,

    created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),

    PRIMARY KEY (id),

    -- Same provider page can legitimately be collected by another run.
    -- The pair below prevents accidental duplicate load in the same run.
    UNIQUE KEY uk_sponsorship_bronze_run_position (
        ingestion_run_id,
        page_number,
        source_record_number
    ),

    KEY idx_sponsorship_bronze_business_date (
        business_date
    ),
    KEY idx_sponsorship_bronze_source_hash (
        source_hash
    ),
    KEY idx_sponsorship_bronze_scope_date (
        scope_id,
        business_date
    ),

    CONSTRAINT ck_sponsorship_bronze_payload_json
        CHECK (
            JSON_VALID(payload)
        ),

    CONSTRAINT ck_sponsorship_bronze_context_json
        CHECK (
            request_context IS NULL
            OR JSON_VALID(request_context)
        )
)
ENGINE=InnoDB
DEFAULT CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
