-- Setup report notification system
-- Add notification template for report alerts
INSERT INTO notification_templates (
  workflow_id,
  name,
  description,
  category,
  is_active
) VALUES (
  'report-alert',
  'Report Alert',
  'Notification sent to moderators when a new report is submitted',
  'moderation',
  true
)
ON CONFLICT (workflow_id) DO UPDATE SET
  name = EXCLUDED.name,
  description = EXCLUDED.description,
  is_active = EXCLUDED.is_active;

-- Create trigger function to notify moderators on new reports
CREATE OR REPLACE FUNCTION public.notify_moderators_on_new_report()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
DECLARE
  reporter_profile record;
  function_url text;
  anon_key text;
  entity_preview text;
BEGIN
  -- Get reporter's username or display name
  SELECT username, display_name INTO reporter_profile
  FROM public.profiles
  WHERE user_id = NEW.reporter_id;
  
  -- Build entity preview based on reported entity type
  entity_preview := CASE NEW.reported_entity_type
    WHEN 'review' THEN
      (SELECT 
        COALESCE(LEFT(review_text, 150), '') || 
        ' (Rating: ' || rating::text || '/5)'
      FROM public.reviews
      WHERE id = NEW.reported_entity_id
      LIMIT 1)
      
    WHEN 'profile' THEN
      (SELECT 
        'User: ' || COALESCE(display_name, username, 'Unknown')
      FROM public.profiles
      WHERE user_id = NEW.reported_entity_id
      LIMIT 1)
      
    WHEN 'content_submission' THEN
      (SELECT 
        submission_type || ' submission: ' || 
        COALESCE(content->>'name', 'Unnamed')
      FROM public.content_submissions
      WHERE id = NEW.reported_entity_id
      LIMIT 1)
      
    ELSE
      'Unknown entity'
  END;
  
  -- Truncate preview to 200 characters and ensure it's not null
  entity_preview := COALESCE(LEFT(entity_preview, 200), 'Entity preview unavailable');
  
  -- Build the function URL
  function_url := 'https://ydvtmnrszybqnbcqbdcy.supabase.co/functions/v1/notify-moderators-report';
  
  -- Use the public anon key
  anon_key := 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4';
  
  -- Call edge function asynchronously with enhanced data
  PERFORM net.http_post(
    url := function_url,
    headers := jsonb_build_object(
      'Content-Type', 'application/json',
      'Authorization', 'Bearer ' || anon_key,
      'apikey', anon_key
    ),
    body := jsonb_build_object(
      'reportId', NEW.id::text,
      'reportType', NEW.report_type,
      'reportedEntityType', NEW.reported_entity_type,
      'reportedEntityId', NEW.reported_entity_id::text,
      'reporterName', COALESCE(reporter_profile.display_name, reporter_profile.username, 'Anonymous'),
      'reason', COALESCE(NEW.reason, 'No reason provided'),
      'entityPreview', entity_preview,
      'reportedAt', to_char(NEW.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')
    )
  );
  
  RETURN NEW;
EXCEPTION
  WHEN OTHERS THEN
    -- Log error but don't fail the report submission
    RAISE WARNING 'Failed to notify moderators about report: %', SQLERRM;
    RETURN NEW;
END;
$function$;

-- Create trigger on reports table
DROP TRIGGER IF EXISTS notify_moderators_on_report_insert ON public.reports;

CREATE TRIGGER notify_moderators_on_report_insert
  AFTER INSERT ON public.reports
  FOR EACH ROW
  EXECUTE FUNCTION public.notify_moderators_on_new_report();