-- Create notification_templates table
CREATE TABLE public.notification_templates (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  workflow_id TEXT NOT NULL UNIQUE,
  name TEXT NOT NULL,
  description TEXT,
  category TEXT NOT NULL,
  novu_workflow_id TEXT,
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

-- Create notification_logs table
CREATE TABLE public.notification_logs (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  user_id UUID NOT NULL,
  template_id UUID REFERENCES public.notification_templates(id),
  novu_transaction_id TEXT,
  channel TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending',
  payload JSONB,
  error_message TEXT,
  delivered_at TIMESTAMP WITH TIME ZONE,
  read_at TIMESTAMP WITH TIME ZONE,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

-- Create notification_channels table
CREATE TABLE public.notification_channels (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  channel_type TEXT NOT NULL,
  name TEXT NOT NULL,
  description TEXT,
  is_enabled BOOLEAN DEFAULT true,
  configuration JSONB DEFAULT '{}'::jsonb,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

-- Create user_notification_preferences table (enhanced)
CREATE TABLE public.user_notification_preferences (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  user_id UUID NOT NULL UNIQUE,
  novu_subscriber_id TEXT,
  channel_preferences JSONB NOT NULL DEFAULT '{
    "in_app": true,
    "email": true,
    "push": false,
    "sms": false
  }'::jsonb,
  workflow_preferences JSONB NOT NULL DEFAULT '{}'::jsonb,
  frequency_settings JSONB NOT NULL DEFAULT '{
    "digest": "daily",
    "max_per_hour": 10
  }'::jsonb,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

-- Enable RLS
ALTER TABLE public.notification_templates ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.notification_logs ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.notification_channels ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_notification_preferences ENABLE ROW LEVEL SECURITY;

-- RLS Policies for notification_templates
CREATE POLICY "Public read access to notification templates"
  ON public.notification_templates FOR SELECT
  USING (true);

CREATE POLICY "Admins can manage notification templates"
  ON public.notification_templates FOR ALL
  USING (is_moderator(auth.uid()));

-- RLS Policies for notification_logs
CREATE POLICY "Users can view their own notification logs"
  ON public.notification_logs FOR SELECT
  USING (auth.uid() = user_id);

CREATE POLICY "Moderators can view all notification logs"
  ON public.notification_logs FOR SELECT
  USING (is_moderator(auth.uid()));

CREATE POLICY "System can insert notification logs"
  ON public.notification_logs FOR INSERT
  WITH CHECK (true);

-- RLS Policies for notification_channels
CREATE POLICY "Public read access to notification channels"
  ON public.notification_channels FOR SELECT
  USING (true);

CREATE POLICY "Admins can manage notification channels"
  ON public.notification_channels FOR ALL
  USING (is_moderator(auth.uid()));

-- RLS Policies for user_notification_preferences
CREATE POLICY "Users can manage their own notification preferences"
  ON public.user_notification_preferences FOR ALL
  USING (auth.uid() = user_id);

CREATE POLICY "Moderators can view all notification preferences"
  ON public.user_notification_preferences FOR SELECT
  USING (is_moderator(auth.uid()));

-- Create indexes
CREATE INDEX idx_notification_logs_user_id ON public.notification_logs(user_id);
CREATE INDEX idx_notification_logs_status ON public.notification_logs(status);
CREATE INDEX idx_notification_logs_created_at ON public.notification_logs(created_at DESC);
CREATE INDEX idx_user_notification_preferences_user_id ON public.user_notification_preferences(user_id);
CREATE INDEX idx_user_notification_preferences_novu_subscriber_id ON public.user_notification_preferences(novu_subscriber_id);

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

CREATE TRIGGER update_notification_channels_updated_at
  BEFORE UPDATE ON public.notification_channels
  FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();

CREATE TRIGGER update_user_notification_preferences_updated_at
  BEFORE UPDATE ON public.user_notification_preferences
  FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();

-- Insert default notification channels
INSERT INTO public.notification_channels (channel_type, name, description) VALUES
  ('in_app', 'In-App Notifications', 'Real-time notifications within the application'),
  ('email', 'Email Notifications', 'Email notifications sent to user''s registered email'),
  ('push', 'Push Notifications', 'Browser push notifications'),
  ('sms', 'SMS Notifications', 'Text message notifications (optional)');

-- Insert default notification templates
INSERT INTO public.notification_templates (workflow_id, name, description, category) VALUES
  ('review-reply', 'Review Reply', 'Notification when someone replies to your review', 'engagement'),
  ('new-follower', 'New Follower', 'Notification when someone follows you', 'social'),
  ('system-announcement', 'System Announcement', 'Important system-wide announcements', 'system'),
  ('weekly-digest', 'Weekly Digest', 'Weekly summary of activity', 'digest'),
  ('monthly-digest', 'Monthly Digest', 'Monthly summary of activity', 'digest'),
  ('moderation-alert', 'Moderation Alert', 'Notification for moderators about pending content', 'moderation'),
  ('content-approved', 'Content Approved', 'Notification when your submitted content is approved', 'moderation'),
  ('content-rejected', 'Content Rejected', 'Notification when your submitted content is rejected', 'moderation');