package webui

import (
	"net/http"
	"strconv"
	"strings"
)

// webmailRulesList is the self-service mirror of rulesList (mailbox_rules.go) — same
// underlying CRUD (ListRulesForMailbox/CreateRule/RemoveRule), just reached from the
// mailbox owner's own portal instead of an admin managing it on their behalf.
func (a *App) webmailRulesList(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	rules, err := a.DB.ListRulesForMailbox(mbox.ID)
	if err != nil {
		setFlash(w, "error", "Error loading rules")
	}
	a.render(w, r, "webmail_rules.html", M{"mailbox": mbox, "rules": rules, "flashes": popFlashes(w, r)})
}

func (a *App) webmailAddRule(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	if err := r.ParseForm(); err != nil {
		setFlash(w, "error", "Invalid form submission")
		http.Redirect(w, r, MailboxPrefix+"/rules", http.StatusFound)
		return
	}
	priority, _ := strconv.Atoi(r.FormValue("priority"))
	matchType := r.FormValue("match_type")
	action := r.FormValue("action")
	actionValue := strings.TrimSpace(r.FormValue("action_value"))

	conditions, ok := parseRuleConditions(r)
	if !ok || !validActions[action] {
		setFlash(w, "error", "Please fill in a valid condition and action")
		http.Redirect(w, r, MailboxPrefix+"/rules", http.StatusFound)
		return
	}
	if action == "move_to_folder" && actionValue == "" {
		setFlash(w, "error", "Please name the folder to move matching mail into")
		http.Redirect(w, r, MailboxPrefix+"/rules", http.StatusFound)
		return
	}
	if _, err := a.DB.CreateRuleMulti(mbox.ID, priority, conditions, matchType, action, actionValue); err != nil {
		setFlash(w, "error", "Error creating rule")
	} else {
		setFlash(w, "success", "Rule added")
	}
	http.Redirect(w, r, MailboxPrefix+"/rules", http.StatusFound)
}

func (a *App) webmailRemoveRule(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	ruleID := int64(atoi(r.PathValue("rule_id")))
	if err := a.DB.RemoveRule(ruleID, mbox.ID); err != nil {
		setFlash(w, "error", "Error removing rule")
	} else {
		setFlash(w, "success", "Rule removed")
	}
	http.Redirect(w, r, MailboxPrefix+"/rules", http.StatusFound)
}
