CREATE TABLE IF NOT EXISTS social_oauth_states (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    user_id BIGINT UNSIGNED NOT NULL,
    state_hash CHAR(64) NOT NULL,
    provider VARCHAR(40) NOT NULL,
    return_to TEXT NOT NULL,
    expires_at DATETIME NOT NULL,
    used_at DATETIME NULL,
    created_at DATETIME NOT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uniq_social_oauth_state_hash (state_hash),
    KEY idx_social_oauth_state_expiry (expires_at),
    CONSTRAINT fk_social_oauth_state_user FOREIGN KEY (user_id) REFERENCES auth_users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS social_connections (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    user_id BIGINT UNSIGNED NOT NULL,
    provider VARCHAR(40) NOT NULL,
    provider_account_id VARCHAR(190) NOT NULL,
    display_name VARCHAR(190) NULL,
    email VARCHAR(190) NULL,
    access_token_encrypted TEXT NOT NULL,
    scopes TEXT NULL,
    expires_at DATETIME NULL,
    status VARCHAR(30) NOT NULL DEFAULT 'connected',
    metadata_json JSON NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uniq_social_connection (user_id, provider, provider_account_id),
    KEY idx_social_connection_provider_status (provider, status),
    CONSTRAINT fk_social_connection_user FOREIGN KEY (user_id) REFERENCES auth_users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS social_publish_logs (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    connection_id BIGINT UNSIGNED NOT NULL,
    idempotency_key VARCHAR(100) NOT NULL,
    author_urn VARCHAR(255) NOT NULL,
    commentary TEXT NOT NULL,
    provider_post_urn VARCHAR(255) NULL,
    status VARCHAR(30) NOT NULL,
    error_message TEXT NULL,
    created_at DATETIME NOT NULL,
    published_at DATETIME NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uniq_social_publish_idempotency (idempotency_key),
    KEY idx_social_publish_connection (connection_id, created_at),
    CONSTRAINT fk_social_publish_connection FOREIGN KEY (connection_id) REFERENCES social_connections(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
