-- Enable RLS on approval_transaction_metrics table
ALTER TABLE approval_transaction_metrics ENABLE ROW LEVEL SECURITY;

-- Policy: Only moderators and admins can view metrics
CREATE POLICY "Moderators can view approval metrics"
ON approval_transaction_metrics
FOR SELECT
TO authenticated
USING (
  EXISTS (
    SELECT 1 FROM user_roles
    WHERE user_roles.user_id = auth.uid()
    AND user_roles.role IN ('moderator', 'admin', 'superuser')
  )
);

-- Policy: System can insert metrics (SECURITY DEFINER functions)
CREATE POLICY "System can insert approval metrics"
ON approval_transaction_metrics
FOR INSERT
TO authenticated
WITH CHECK (true);

COMMENT ON POLICY "Moderators can view approval metrics" ON approval_transaction_metrics IS 
'Allows moderators, admins, and superusers to view approval transaction metrics for monitoring and analytics';

COMMENT ON POLICY "System can insert approval metrics" ON approval_transaction_metrics IS 
'Allows the process_approval_transaction function to log metrics. The function is SECURITY DEFINER so it runs with elevated privileges';