-- Fix log_moderation_action to write to relational moderation_audit_metadata table
-- Removes reference to non-existent metadata column

CREATE OR REPLACE FUNCTION public.log_moderation_action(
  _submission_id UUID,
  _action TEXT,
  _previous_status TEXT DEFAULT NULL,
  _new_status TEXT DEFAULT NULL,
  _notes TEXT DEFAULT NULL,
  _metadata JSONB DEFAULT '{}'::jsonb
)
RETURNS UUID
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  _log_id UUID;
  _metadata_record record;
BEGIN
  -- Insert into moderation_audit_log (without metadata JSONB column)
  INSERT INTO public.moderation_audit_log (
    submission_id,
    moderator_id,
    action,
    previous_status,
    new_status,
    notes
  ) VALUES (
    _submission_id,
    auth.uid(),
    _action,
    _previous_status,
    _new_status,
    _notes
  )
  RETURNING id INTO _log_id;
  
  -- Write metadata to relational moderation_audit_metadata table
  IF _metadata IS NOT NULL AND jsonb_typeof(_metadata) = 'object' THEN
    FOR _metadata_record IN
      SELECT key, value::text as text_value
      FROM jsonb_each_text(_metadata)
    LOOP
      INSERT INTO public.moderation_audit_metadata (
        audit_log_id,
        metadata_key,
        metadata_value
      ) VALUES (
        _log_id,
        _metadata_record.key,
        _metadata_record.text_value
      );
    END LOOP;
  END IF;
  
  RETURN _log_id;
END;
$$;

COMMENT ON FUNCTION public.log_moderation_action(UUID, TEXT, TEXT, TEXT, TEXT, JSONB) IS 
  'Logs moderation actions with metadata stored relationally in moderation_audit_metadata table';