-- Fix security warnings for idempotency system

-- 1. Fix Function Search Path: Add explicit search_path to cleanup function
CREATE OR REPLACE FUNCTION cleanup_expired_idempotency_keys()
RETURNS INTEGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
  deleted_count INTEGER;
BEGIN
  DELETE FROM submission_idempotency_keys
  WHERE expires_at < now() - interval '1 hour';
  
  GET DIAGNOSTICS deleted_count = ROW_COUNT;
  
  RETURN deleted_count;
END;
$$;

-- 2. Fix Security Definer View: Add RLS to idempotency_stats view
-- Drop and recreate with proper security
DROP VIEW IF EXISTS idempotency_stats;

CREATE VIEW idempotency_stats 
WITH (security_invoker=true)
AS
SELECT
  DATE_TRUNC('hour', created_at) AS hour,
  status,
  COUNT(*) AS total_requests,
  COUNT(DISTINCT moderator_id) AS unique_moderators,
  AVG(duration_ms) AS avg_duration_ms,
  PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY duration_ms) AS p95_duration_ms
FROM submission_idempotency_keys
WHERE created_at > now() - interval '7 days'
GROUP BY DATE_TRUNC('hour', created_at), status
ORDER BY hour DESC, status;

COMMENT ON VIEW idempotency_stats IS 'Monitoring view for idempotency key performance and usage statistics (admin/moderator access only via RLS)';

-- Enable RLS on the view
ALTER VIEW idempotency_stats SET (security_invoker=true);

-- Add RLS policy for the view (admins and moderators only)
-- Note: Views use the underlying table's RLS, so moderators/admins who can access 
-- submission_idempotency_keys can access this view