package db

import "strings"

// TrustedImageSender is one sender a mailbox owner has said to always show remote
// images from (esrv_mailboxes.remote_images_mode = "trusted") — see schema.go's
// comment on esrv_mailbox_trusted_image_senders.
type TrustedImageSender struct {
	ID    int64
	Email string
}

// ListTrustedImageSenders returns a mailbox's trusted-sender list, alphabetically.
func (d *DB) ListTrustedImageSenders(mailboxID int64) ([]TrustedImageSender, error) {
	rows, err := d.Query(`SELECT id, email FROM esrv_mailbox_trusted_image_senders WHERE mailbox_id = ? ORDER BY email`, mailboxID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []TrustedImageSender
	for rows.Next() {
		var t TrustedImageSender
		if err := rows.Scan(&t.ID, &t.Email); err != nil {
			return nil, err
		}
		out = append(out, t)
	}
	return out, rows.Err()
}

// AddTrustedImageSender is idempotent (INSERT OR IGNORE) — adding an address already
// on the list is a harmless no-op, not an error, since both the settings-page "Add"
// form and the per-message "always allow this sender" checkbox can reach it.
func (d *DB) AddTrustedImageSender(mailboxID int64, email string) error {
	_, err := d.Exec(`INSERT OR IGNORE INTO esrv_mailbox_trusted_image_senders (mailbox_id, email) VALUES (?, ?)`,
		mailboxID, strings.ToLower(strings.TrimSpace(email)))
	return err
}

func (d *DB) RemoveTrustedImageSender(id, mailboxID int64) error {
	_, err := d.Exec(`DELETE FROM esrv_mailbox_trusted_image_senders WHERE id = ? AND mailbox_id = ?`, id, mailboxID)
	return err
}

// IsTrustedImageSender reports whether email is on mailboxID's trusted list —
// case-insensitive, since email local-parts/domains are conventionally
// case-insensitive and a header's casing is never guaranteed to match what was typed
// into the settings page.
func (d *DB) IsTrustedImageSender(mailboxID int64, email string) (bool, error) {
	var n int
	err := d.QueryRow(`SELECT COUNT(*) FROM esrv_mailbox_trusted_image_senders WHERE mailbox_id = ? AND email = ?`,
		mailboxID, strings.ToLower(strings.TrimSpace(email))).Scan(&n)
	return n > 0, err
}
