package webui

import (
	"net/http"
	"strings"
)

// listsPage shows a mailbox's allow-list and block-list entries plus forms to add to
// either. A single handler set keyed by list_type, backing the single
// esrv_mailbox_allowblock table (not two near-identical resources).
func (a *App) listsPage(w http.ResponseWriter, r *http.Request) {
	mailbox, ok := a.mailboxWithAccess(w, r)
	if !ok {
		return
	}
	entries, err := a.DB.ListAllowBlock(mailbox.ID)
	if err != nil {
		setFlash(w, "error", "Error loading lists")
	}
	var allow, block []any
	for _, e := range entries {
		if e.ListType == "allow" {
			allow = append(allow, e)
		} else {
			block = append(block, e)
		}
	}
	a.render(w, r, "mailbox_lists.html", M{"active": "mailboxes", "mailbox": mailbox, "allow": allow, "block": block})
}

func (a *App) addAllowBlockEntry(w http.ResponseWriter, r *http.Request) {
	mailbox, ok := a.mailboxWithAccess(w, r)
	if !ok {
		return
	}
	listType := r.FormValue("list_type")
	pattern := strings.ToLower(strings.TrimSpace(r.FormValue("pattern")))
	if (listType != "allow" && listType != "block") || pattern == "" {
		setFlash(w, "error", "Please provide a valid address or @domain pattern")
		http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/lists", http.StatusFound)
		return
	}
	if _, err := a.DB.AddAllowBlockEntry(mailbox.ID, listType, pattern); err != nil {
		setFlash(w, "error", "Error adding entry")
	} else {
		setFlash(w, "success", "Entry added")
	}
	http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/lists", http.StatusFound)
}

func (a *App) removeAllowBlockEntry(w http.ResponseWriter, r *http.Request) {
	mailbox, ok := a.mailboxWithAccess(w, r)
	if !ok {
		return
	}
	entryID := int64(atoi(r.PathValue("entry_id")))
	if err := a.DB.RemoveAllowBlockEntry(entryID, mailbox.ID); err != nil {
		setFlash(w, "error", "Error removing entry")
	} else {
		setFlash(w, "success", "Entry removed")
	}
	http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/lists", http.StatusFound)
}
