-- Fix security warnings from span storage schema

-- Drop and recreate views with SECURITY INVOKER
DROP VIEW IF EXISTS public.trace_summary;
DROP VIEW IF EXISTS public.span_hierarchy;

-- Recreate trace_summary with SECURITY INVOKER
CREATE VIEW public.trace_summary
WITH (security_invoker = true)
AS
SELECT
  trace_id,
  COUNT(*) as span_count,
  MIN(start_time) as trace_start,
  MAX(end_time) as trace_end,
  SUM(duration_ms) as total_duration_ms,
  COUNT(*) FILTER (WHERE status = 'error') as error_count,
  ARRAY_AGG(DISTINCT name) as span_names,
  ARRAY_AGG(span_id ORDER BY start_time) as span_ids
FROM public.request_spans
GROUP BY trace_id;

-- Recreate span_hierarchy with SECURITY INVOKER
CREATE VIEW public.span_hierarchy
WITH (security_invoker = true)
AS
WITH RECURSIVE span_tree AS (
  -- Root spans (no parent)
  SELECT
    span_id,
    parent_span_id,
    trace_id,
    name,
    kind,
    start_time,
    duration_ms,
    status,
    1 as depth,
    ARRAY[span_id] as path
  FROM public.request_spans
  WHERE parent_span_id IS NULL
  
  UNION ALL
  
  -- Child spans
  SELECT
    rs.span_id,
    rs.parent_span_id,
    rs.trace_id,
    rs.name,
    rs.kind,
    rs.start_time,
    rs.duration_ms,
    rs.status,
    st.depth + 1,
    st.path || rs.span_id
  FROM public.request_spans rs
  INNER JOIN span_tree st ON rs.parent_span_id = st.span_id
)
SELECT * FROM span_tree;

-- Recreate function with explicit search_path
CREATE OR REPLACE FUNCTION public.cleanup_old_spans()
RETURNS integer
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  deleted_count integer;
BEGIN
  -- Delete spans older than 30 days
  DELETE FROM public.request_spans
  WHERE created_at < now() - interval '30 days';
  
  GET DIAGNOSTICS deleted_count = ROW_COUNT;
  
  RETURN deleted_count;
END;
$$;