-- name: migration-0000-create-email-spool#
CREATE TABLE IF NOT EXISTS email_spool (
   id INTEGER PRIMARY KEY AUTOINCREMENT
 , user_id INTEGER NOT NULL
 , subject TEXT
 , body TEXT
 , sent_at TEXT
 , FOREIGN KEY(user_id) REFERENCES users(id)
);

-- name: create-email!
INSERT INTO email_spool (
   user_id
 , subject
 , body
) VALUES (
   :uid
 , :subject
 , :body
)
RETURNING
   id
;

-- name: send-email!
UPDATE email_spool
SET
   sent_at = datetime('now')
WHERE
   id = :eid
;

-- name: poll-email-queue
SELECT
   s.id as `id`
 , u.email as `to`
 , subject
 , body
FROM email_spool s
INNER JOIN users u
   ON s.user_id = u.id
WHERE
   s.sent_at IS NULL
LIMIT 1
;
