-- Notification Categories
CREATE TABLE notification_categories (
    id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
    name VARCHAR(100) NOT NULL,
    value VARCHAR(50) UNIQUE NOT NULL,
    description TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Notification Templates
CREATE TABLE notification_templates (
    id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
    name VARCHAR(100) NOT NULL,
    value VARCHAR(50) UNIQUE NOT NULL,
    subject VARCHAR(255),
    email_content TEXT,
    push_title VARCHAR(100),
    push_body VARCHAR(300),
    variables JSON DEFAULT ('[]'),
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- User Segments
CREATE TABLE user_segments (
    id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
    name VARCHAR(100) NOT NULL,
    value VARCHAR(50) UNIQUE NOT NULL,
    description TEXT,
    criteria JSON NOT NULL,
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Main Notifications Table
CREATE TABLE notifications (
    id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
    title VARCHAR(255) NOT NULL,
    type VARCHAR(20) NOT NULL CHECK (type IN ('single', 'bulk')),
    priority VARCHAR(20) NOT NULL CHECK (priority IN ('low', 'medium', 'high', 'critical')),
    category_id VARCHAR(36),
    status VARCHAR(20) DEFAULT 'draft' CHECK (status IN ('draft', 'scheduled', 'sending', 'sent', 'failed', 'cancelled')),
    
    -- Scheduling
    delivery_type VARCHAR(20) NOT NULL CHECK (delivery_type IN ('immediate', 'scheduled')),
    scheduled_at TIMESTAMP NULL,
    timezone VARCHAR(50) DEFAULT 'UTC',
    expires_at TIMESTAMP NULL,
    
    -- A/B Testing
    enable_ab_testing BOOLEAN DEFAULT false,
    ab_test_split INTEGER DEFAULT 50 CHECK (ab_test_split BETWEEN 10 AND 90),
    ab_test_name VARCHAR(100),
    
    -- Tracking & Analytics
    enable_tracking BOOLEAN DEFAULT true,
    
    -- Audience Settings
    audience_type VARCHAR(20) NOT NULL CHECK (audience_type IN ('all', 'specific', 'segmented')),
    specific_users TEXT, -- Comma-separated user IDs or emails
    user_status VARCHAR(20),
    registration_period VARCHAR(50),
    exclude_unsubscribed BOOLEAN DEFAULT true,
    respect_do_not_disturb BOOLEAN DEFAULT true,
    
    -- Content
    content_type VARCHAR(20) NOT NULL CHECK (content_type IN ('new', 'template')),
    template_id VARCHAR(36),
    
    -- Email Content
    email_subject VARCHAR(255),
    email_content TEXT,
    call_to_action_text VARCHAR(100),
    call_to_action_url TEXT,
    
    -- Push Content
    push_title VARCHAR(100),
    push_body VARCHAR(300),
    push_image_url TEXT,
    
    -- Metadata
    estimated_reach INTEGER DEFAULT 0,
    actual_sent INTEGER DEFAULT 0,
    created_by VARCHAR(36) NOT NULL, -- User ID who created this
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    sent_at TIMESTAMP NULL,
    
    FOREIGN KEY (category_id) REFERENCES notification_categories(id),
    FOREIGN KEY (template_id) REFERENCES notification_templates(id)
);

-- Notification Channels (Many-to-Many)
CREATE TABLE notification_channels (
    id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
    notification_id VARCHAR(36) NOT NULL,
    channel_type VARCHAR(20) NOT NULL CHECK (channel_type IN ('email', 'push', 'sms', 'in_app')),
    is_enabled BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (notification_id) REFERENCES notifications(id) ON DELETE CASCADE
);

-- Notification User Segments (Many-to-Many)
CREATE TABLE notification_user_segments (
    id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
    notification_id VARCHAR(36) NOT NULL,
    segment_id VARCHAR(36) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (notification_id) REFERENCES notifications(id) ON DELETE CASCADE,
    FOREIGN KEY (segment_id) REFERENCES user_segments(id)
);

-- Notification Recipients (For tracking who received what)
CREATE TABLE notification_recipients (
    id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
    notification_id VARCHAR(36) NOT NULL,
    user_id VARCHAR(36) NOT NULL,
    email VARCHAR(255),
    channel_type VARCHAR(20) NOT NULL,
    status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'delivered', 'failed', 'bounced')),
    sent_at TIMESTAMP NULL,
    delivered_at TIMESTAMP NULL,
    opened_at TIMESTAMP NULL,
    clicked_at TIMESTAMP NULL,
    error_message TEXT,
    ab_test_variant VARCHAR(1) CHECK (ab_test_variant IN ('A', 'B')),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (notification_id) REFERENCES notifications(id) ON DELETE CASCADE
);

-- Notification Queue (For scheduled notifications)
CREATE TABLE notification_queue (
    id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
    notification_id VARCHAR(36) NOT NULL,
    recipient_id VARCHAR(36) NOT NULL,
    scheduled_for TIMESTAMP NOT NULL,
    priority INTEGER DEFAULT 5,
    attempts INTEGER DEFAULT 0,
    max_attempts INTEGER DEFAULT 3,
    status VARCHAR(20) DEFAULT 'queued' CHECK (status IN ('queued', 'processing', 'sent', 'failed', 'cancelled')),
    last_attempt_at TIMESTAMP NULL,
    error_message TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (notification_id) REFERENCES notifications(id) ON DELETE CASCADE,
    FOREIGN KEY (recipient_id) REFERENCES notification_recipients(id) ON DELETE CASCADE
);

-- Notification Analytics
CREATE TABLE notification_analytics (
    id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
    notification_id VARCHAR(36) NOT NULL,
    channel_type VARCHAR(20) NOT NULL,
    metric_type VARCHAR(30) NOT NULL CHECK (metric_type IN ('sent', 'delivered', 'opened', 'clicked', 'bounced', 'unsubscribed')),
    metric_value INTEGER DEFAULT 0,
    recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    metadata JSON DEFAULT ('{}'),
    FOREIGN KEY (notification_id) REFERENCES notifications(id) ON DELETE CASCADE
);

-- User Notification Preferences
CREATE TABLE user_notification_preferences (
    id VARCHAR(36) PRIMARY KEY DEFAULT (UUID()),
    user_id VARCHAR(36) NOT NULL,
    channel_type VARCHAR(20) NOT NULL,
    category_value VARCHAR(50),
    is_enabled BOOLEAN DEFAULT true,
    do_not_disturb_start TIME,
    do_not_disturb_end TIME,
    timezone VARCHAR(50) DEFAULT 'UTC',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE(user_id, channel_type, category_value)
);

-- Indexes for better performance
CREATE INDEX idx_notifications_status ON notifications(status);
CREATE INDEX idx_notifications_scheduled_at ON notifications(scheduled_at);
CREATE INDEX idx_notifications_created_by ON notifications(created_by);
CREATE INDEX idx_notification_recipients_user_id ON notification_recipients(user_id);
CREATE INDEX idx_notification_recipients_status ON notification_recipients(status);
CREATE INDEX idx_notification_queue_scheduled_for ON notification_queue(scheduled_for);
CREATE INDEX idx_notification_queue_status ON notification_queue(status);
CREATE INDEX idx_notification_analytics_notification_id ON notification_analytics(notification_id);
CREATE INDEX idx_user_notification_preferences_user_id ON user_notification_preferences(user_id);

-- Insert default categories
INSERT INTO notification_categories (name, value, description) VALUES
('User Management', 'user_management', 'User registration, profile updates, account changes'),
('Orders & Transactions', 'orders', 'Order confirmations, payment notifications, transaction updates'),
('Security & Authentication', 'security', 'Login alerts, password changes, security notifications'),
('Marketing & Promotions', 'marketing', 'Promotional offers, newsletters, product announcements'),
('System Updates', 'system', 'System maintenance, feature updates, service announcements'),
('General Information', 'general', 'General notifications and information');

-- Insert default templates
INSERT INTO notification_templates (name, value, subject, email_content, push_title, push_body, variables) VALUES
('Welcome Message', 'welcome', 'Welcome to {{company_name}}!', 
 '<h1>Welcome {{first_name}}!</h1><p>Thank you for joining {{company_name}}. We''re excited to have you on board.</p>', 
 'Welcome to {{company_name}}!', 'Hi {{first_name}}, welcome to our platform!', 
 '["first_name", "last_name", "company_name"]'),
('Password Reset', 'password_reset', 'Reset your password', 
 '<h1>Password Reset Request</h1><p>Hi {{first_name}}, click the link below to reset your password.</p>', 
 'Password Reset', 'Tap to reset your password', 
 '["first_name"]'),
('Order Confirmation', 'order_confirmation', 'Order Confirmation #{{order_id}}', 
 '<h1>Order Confirmed!</h1><p>Thank you {{first_name}}, your order #{{order_id}} has been confirmed.</p>', 
 'Order Confirmed!', 'Your order #{{order_id}} is confirmed', 
 '["first_name", "order_id", "order_total"]');

-- Insert default user segments
INSERT INTO user_segments (name, value, description, criteria) VALUES
('New Users', 'new_users', 'Users registered within last 30 days', '{"registration_days": 30}'),
('Active Users', 'active_users', 'Users active in last 7 days', '{"last_activity_days": 7}'),
('Premium Subscribers', 'premium_users', 'Users with premium subscription', '{"subscription_type": "premium"}'),
('Inactive Users', 'inactive_users', 'Users not active in 30+ days', '{"inactive_days": 30}'),
('High-Value Customers', 'high_value', 'Customers with high lifetime value', '{"min_order_value": 1000}'),
('Mobile App Users', 'mobile_users', 'Users who use mobile app', '{"platform": "mobile"}'); 