CREATE TABLE IF NOT EXISTS email_queue (
    id TEXT PRIMARY KEY,
    notification_id TEXT,
    to_address TEXT NOT NULL,
    subject TEXT NOT NULL,
    body TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'sent', 'failed', 'skipped')),
    attempts INTEGER NOT NULL DEFAULT 0,
    max_attempts INTEGER NOT NULL DEFAULT 3,
    last_error TEXT,
    next_attempt_at TEXT NOT NULL,
    sent_at TEXT,
    created_at TEXT NOT NULL,
    FOREIGN KEY(notification_id) REFERENCES notifications(id) ON DELETE SET NULL
);

CREATE INDEX IF NOT EXISTS idx_email_queue_status ON email_queue(status, next_attempt_at);
CREATE INDEX IF NOT EXISTS idx_email_queue_notification ON email_queue(notification_id);
