-- ============================================
-- 此文件由 Meoo Cloud 自动生成，请勿修改
-- This file is auto-generated by Meoo Cloud, DO NOT MODIFY
-- ============================================


CREATE TABLE IF NOT EXISTS data_audit_logs (
 id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
 table_name TEXT NOT NULL,
 record_id UUID NOT NULL,
 operation TEXT NOT NULL CHECK (operation IN ('INSERT', 'UPDATE', 'DELETE')),
 old_values JSONB,
 new_values JSONB,
 changed_by UUID REFERENCES auth.users(id),
 changed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
 validation_passed BOOLEAN NOT NULL DEFAULT TRUE,
 error_message TEXT
);

CREATE INDEX IF NOT EXISTS idx_audit_logs_table_record ON data_audit_logs(table_name, record_id);
CREATE INDEX IF NOT EXISTS idx_audit_logs_changed_at ON data_audit_logs(changed_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_logs_validation ON data_audit_logs(validation_passed) WHERE validation_passed = FALSE;

ALTER TABLE data_audit_logs ENABLE ROW LEVEL SECURITY;

CREATE POLICY admin_select_audit_logs ON data_audit_logs
 FOR SELECT USING (true);

CREATE POLICY system_insert_audit_logs ON data_audit_logs
 FOR INSERT WITH CHECK (true);

