// A support desk reading an old POP3 mailbox: what waits there, a customer's reply read (with
// the line that starts with a dot kept), an invoice's headers and attachment, one message
// deleted for good at QUIT, and a wrong password.
//
//   POP3_URL=pop3s://desk:secret@mail.example.com quillo run pop3.qwe      then open http://localhost:8080/inbox
//
// Needs a POP3 server at POP3_URL (pop3:// upgrades with STLS, pop3s:// is TLS from the start).
// POP3_CA is a CA's PEM (text or file) for a server with a private certificate.

use "pop3.qwer"

let URL = env("POP3_URL", "pop3s://desk:secret@127.0.0.1")
let OPTS = { starttls: "required", ca: env("POP3_CA", ""), timeout_ms: 5000 }

route GET /inbox = {
    stat: pop3_stat(URL, OPTS)?,
    messages: pop3_list(URL, OPTS)?,
}

route GET /read {
    let m = pop3_retr(URL, "uid-101", OPTS)?
    { subject: m.subject, from: m.from.email, date: m.date, in_reply_to: m.in_reply_to, text: m.text }
}

route GET /invoice {
    let head = pop3_top(URL, 2, 0, OPTS)?
    let m = pop3_retr(URL, 2, OPTS)?
    { subject: head.subject, from: head.from.name, attachments: m.attachments, html: m.html != null }
}

// The newsletter goes: marked, then deleted when the session ends; the next session has one less.
route GET /delete {
    let before = pop3_stat(URL, OPTS)?.count
    pop3_dele(URL, "uid-103", OPTS)?
    pop3_quit(URL)?
    { before, after: pop3_stat(URL, OPTS)?.count }
}

route GET /wrong = { error: pop3_stat(replace(URL, "s3cret", "guess"), OPTS).error }
