CREATE TABLE IF NOT EXISTS `email_logs` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `template_id` INT UNSIGNED DEFAULT NULL,
    `mailbox_id` INT UNSIGNED DEFAULT NULL,
    `order_id` INT UNSIGNED DEFAULT NULL,
    `recipient_email` VARCHAR(255) NOT NULL,
    `recipient_name` VARCHAR(200) DEFAULT NULL,
    `subject` VARCHAR(500) NOT NULL,
    `body_html` TEXT NOT NULL,
    `attachments_json` JSON DEFAULT NULL,
    `status` ENUM('sent','failed','pending') NOT NULL DEFAULT 'pending',
    `error_message` TEXT DEFAULT NULL,
    `sent_at` DATETIME DEFAULT NULL,
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `idx_email_logs_template` (`template_id`),
    KEY `idx_email_logs_mailbox` (`mailbox_id`),
    KEY `idx_email_logs_order` (`order_id`),
    KEY `idx_email_logs_status` (`status`),
    KEY `idx_email_logs_sent_at` (`sent_at`),
    CONSTRAINT `fk_email_logs_template` FOREIGN KEY (`template_id`) REFERENCES `email_templates` (`id`) ON DELETE SET NULL,
    CONSTRAINT `fk_email_logs_mailbox` FOREIGN KEY (`mailbox_id`) REFERENCES `email_mailboxes` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
