package webui

import (
	"net/http"
	"strings"

	"mailgoserver/internal/db"
)

// webmailListTypes are the only list_types a mailbox owner may self-manage — "block"
// (admin's hard-reject-at-RCPT list) is deliberately excluded, see
// esrv_mailbox_allowblock's schema comment.
var webmailListTypes = map[string]bool{"allow": true, "junk": true}

// webmailBlocklistPage shows a mailbox owner's own Blocklist ("junk" entries — mail
// from these addresses/domains is always quarantined straight to Junk, bypassing
// spam scoring) and Whitelist ("allow" entries — never scored as spam, always lands
// in INBOX; the escape hatch for a trusted sender rspamd or the built-in heuristic
// keeps flagging).
func (a *App) webmailBlocklistPage(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	entries, err := a.DB.ListAllowBlock(mbox.ID)
	if err != nil {
		setFlash(w, "error", "Error loading lists")
	}
	var blocked, allowed []db.MailboxAllowBlockEntry
	for _, e := range entries {
		switch e.ListType {
		case "junk":
			blocked = append(blocked, e)
		case "allow":
			allowed = append(allowed, e)
		}
	}
	a.render(w, r, "webmail_blocklist.html", M{
		"mailbox": mbox, "blocked": blocked, "allowed": allowed,
		"flashes": popFlashes(w, r), "active_section": "blocklist",
	})
}

func (a *App) webmailBlocklistAdd(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	pattern := strings.ToLower(strings.TrimSpace(r.FormValue("pattern")))
	listType := r.FormValue("list_type")
	if pattern == "" || !webmailListTypes[listType] {
		setFlash(w, "error", "Enter an address (or @domain.com) and choose a list")
		http.Redirect(w, r, MailboxPrefix+"/blocklist", http.StatusFound)
		return
	}
	if _, err := a.DB.AddAllowBlockEntry(mbox.ID, listType, pattern); err != nil {
		setFlash(w, "error", "Error adding entry")
	} else {
		setFlash(w, "success", "Added")
	}
	http.Redirect(w, r, MailboxPrefix+"/blocklist", http.StatusFound)
}

func (a *App) webmailBlocklistRemove(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	id := int64(atoi(r.PathValue("id")))
	if err := a.DB.RemoveAllowBlockEntry(id, mbox.ID); err != nil {
		setFlash(w, "error", "Error removing entry")
	} else {
		setFlash(w, "success", "Removed")
	}
	http.Redirect(w, r, MailboxPrefix+"/blocklist", http.StatusFound)
}
