-- V78: 审计日志数据库层防篡改约束
-- PRD要求: sys_audit_log表不可UPDATE/DELETE（仅允许INSERT和SELECT）
-- 使用PostgreSQL触发器实现，在应用层哈希链基础上增加数据库层强约束

-- 创建防篡改函数：阻止对sys_audit_log的UPDATE操作
CREATE OR REPLACE FUNCTION prevent_audit_log_update()
RETURNS TRIGGER AS $$
BEGIN
    RAISE EXCEPTION 'UPDATE on sys_audit_log is forbidden. Audit logs are immutable.'
        USING ERRCODE = '45000';
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- 创建防篡改函数：阻止对sys_audit_log的DELETE操作
CREATE OR REPLACE FUNCTION prevent_audit_log_delete()
RETURNS TRIGGER AS $$
BEGIN
    RAISE EXCEPTION 'DELETE on sys_audit_log is forbidden. Audit logs are immutable.'
        USING ERRCODE = '45000';
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- 创建触发器：每行UPDATE前执行防篡改检查
DROP TRIGGER IF EXISTS trg_prevent_audit_log_update ON sys_audit_log;
CREATE TRIGGER trg_prevent_audit_log_update
    BEFORE UPDATE ON sys_audit_log
    FOR EACH ROW
    EXECUTE FUNCTION prevent_audit_log_update();

-- 创建触发器：每行DELETE前执行防篡改检查
DROP TRIGGER IF EXISTS trg_prevent_audit_log_delete ON sys_audit_log;
CREATE TRIGGER trg_prevent_audit_log_delete
    BEFORE DELETE ON sys_audit_log
    FOR EACH ROW
    EXECUTE FUNCTION prevent_audit_log_delete();

-- 验证触发器创建成功
DO $$
BEGIN
    -- 确认触发器存在
    IF NOT EXISTS (
        SELECT 1 FROM pg_trigger WHERE tgname = 'trg_prevent_audit_log_update'
    ) THEN
        RAISE EXCEPTION 'Failed to create UPDATE trigger for sys_audit_log';
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM pg_trigger WHERE tgname = 'trg_prevent_audit_log_delete'
    ) THEN
        RAISE EXCEPTION 'Failed to create DELETE trigger for sys_audit_log';
    END IF;

    RAISE NOTICE 'Audit log immutability triggers created successfully';
END $$;
