-- Email Management Schema for WHP
-- This script creates the necessary database structure for email account management

USE whp;

-- Create email_accounts table to track email addresses
CREATE TABLE IF NOT EXISTS email_accounts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email_address VARCHAR(255) NOT NULL UNIQUE,
    username VARCHAR(32) NOT NULL,
    domain_name VARCHAR(255) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    quota_mb INT DEFAULT 100,
    active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_email_address (email_address),
    INDEX idx_username (username),
    INDEX idx_domain_name (domain_name),
    INDEX idx_active (active)
);

-- Create email_forwarders table for email forwarding
CREATE TABLE IF NOT EXISTS email_forwarders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    source_email VARCHAR(255) NOT NULL,
    destination_email VARCHAR(255) NOT NULL,
    username VARCHAR(32) NOT NULL,
    active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY unique_forward (source_email, destination_email),
    INDEX idx_source_email (source_email),
    INDEX idx_destination_email (destination_email),
    INDEX idx_username (username),
    INDEX idx_active (active)
);

-- Create email_aliases table for email aliases
CREATE TABLE IF NOT EXISTS email_aliases (
    id INT AUTO_INCREMENT PRIMARY KEY,
    alias_email VARCHAR(255) NOT NULL,
    target_email VARCHAR(255) NOT NULL,
    username VARCHAR(32) NOT NULL,
    active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY unique_alias (alias_email),
    INDEX idx_alias_email (alias_email),
    INDEX idx_target_email (target_email),
    INDEX idx_username (username),
    INDEX idx_active (active)
);

-- Insert initial data if tables are empty
-- (No initial data needed for email management) 