-- Add notification templates for user submission status notifications
INSERT INTO notification_templates (workflow_id, novu_workflow_id, name, description, category, is_active)
VALUES 
  ('submission-approved', 'submission-approved', 'Submission Approved', 'Notify users when their submission is approved', 'submission', true),
  ('submission-rejected', 'submission-rejected', 'Submission Rejected', 'Notify users when their submission is rejected', 'submission', true)
ON CONFLICT (workflow_id) DO NOTHING;

-- Function to notify users when submission status changes
CREATE OR REPLACE FUNCTION public.notify_user_on_submission_status_change()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
  function_url text;
  anon_key text;
BEGIN
  -- Only notify on status changes to approved or rejected
  IF OLD.status IS DISTINCT FROM NEW.status AND NEW.status IN ('approved', 'rejected') THEN
    
    -- Build the function URL
    function_url := 'https://ydvtmnrszybqnbcqbdcy.supabase.co/functions/v1/notify-user-submission-status';
    
    -- Use the public anon key
    anon_key := 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4';
    
    -- Call edge function asynchronously
    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(
        'submission_id', NEW.id,
        'user_id', NEW.user_id,
        'submission_type', NEW.submission_type,
        'status', NEW.status,
        'rejection_reason', NEW.reviewer_notes
      )
    );
    
    RAISE LOG 'Triggered user notification for submission % with status %', NEW.id, NEW.status;
  END IF;
  
  RETURN NEW;
EXCEPTION
  WHEN OTHERS THEN
    -- Log error but don't fail the status update
    RAISE WARNING 'Failed to notify user about submission status: %', SQLERRM;
    RETURN NEW;
END;
$function$;

-- Create trigger on content_submissions
DROP TRIGGER IF EXISTS notify_user_on_submission_status_change_trigger ON content_submissions;
CREATE TRIGGER notify_user_on_submission_status_change_trigger
  AFTER UPDATE ON content_submissions
  FOR EACH ROW
  EXECUTE FUNCTION notify_user_on_submission_status_change();