-- =============================================================================
-- tenant_operations_log — журнал тенант-уровневых операций вне сделок
-- (проекты, API-ключи, исходящий webhook URL, и т.п.). Защищён hash-chain.
-- =============================================================================
CREATE TABLE tenant_operations_log (
    id              BIGSERIAL PRIMARY KEY,
    tenant_id       BIGINT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    user_id         BIGINT REFERENCES users(id),           -- NULL для системных
    entity_type     VARCHAR(50) NOT NULL,                  -- 'project', 'api_key', 'webhook_settings'
    entity_id       BIGINT,                                -- NULL если bulk
    event           VARCHAR(100) NOT NULL,                 -- 'project.created', 'api_key.regenerated', ...
    payload_before  JSONB,
    payload_after   JSONB,
    ip_address      INET,
    user_agent      TEXT,
    log_hash        BYTEA,                                 -- hash chain
    created_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_tenant_ops_tenant_created
    ON tenant_operations_log(tenant_id, created_at DESC);
CREATE INDEX idx_tenant_ops_entity
    ON tenant_operations_log(tenant_id, entity_type, entity_id, created_at DESC)
    WHERE entity_id IS NOT NULL;

ALTER TABLE tenant_operations_log ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON tenant_operations_log
    USING (tenant_id = current_setting('app.current_tenant_id')::bigint);

CREATE TRIGGER trg_audit_chain_hash_tenant_ops
    BEFORE INSERT ON tenant_operations_log
    FOR EACH ROW EXECUTE FUNCTION audit_chain_hash();
CREATE TRIGGER trg_audit_block_mut_tenant_ops
    BEFORE UPDATE OR DELETE ON tenant_operations_log
    FOR EACH ROW EXECUTE FUNCTION audit_block_mutation();
