-- Create admin settings table
CREATE TABLE public.admin_settings (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  setting_key TEXT NOT NULL UNIQUE,
  setting_value JSONB NOT NULL,
  category TEXT NOT NULL,
  description TEXT,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_by UUID REFERENCES auth.users(id)
);

-- Enable RLS
ALTER TABLE public.admin_settings ENABLE ROW LEVEL SECURITY;

-- Create policies for admin settings
CREATE POLICY "Admins can manage settings" 
ON public.admin_settings 
FOR ALL 
USING (is_moderator(auth.uid()));

-- Create trigger for updated_at
CREATE TRIGGER update_admin_settings_updated_at
BEFORE UPDATE ON public.admin_settings
FOR EACH ROW
EXECUTE FUNCTION public.update_updated_at_column();

-- Insert default settings
INSERT INTO public.admin_settings (setting_key, setting_value, category, description) VALUES
('moderation.auto_flag_threshold', '3', 'moderation', 'Number of reports needed to automatically flag content'),
('moderation.require_approval', 'true', 'moderation', 'Require admin approval for new reviews'),
('moderation.ban_durations', '["1d", "7d", "30d", "permanent"]', 'user_management', 'Available ban duration options'),
('notifications.email_alerts', 'true', 'notifications', 'Send email alerts for new reports'),
('notifications.report_threshold', '5', 'notifications', 'Minimum reports to trigger alert'),
('system.audit_retention_days', '365', 'system', 'How long to keep audit logs (days)'),
('system.auto_cleanup', 'false', 'system', 'Automatically clean up old data');