package webui

import (
	"net/http"
	"strings"
)

// aliasesList shows a mailbox's aliases plus a form to add a new one. The alias's
// domain can differ from the mailbox's own — it's resolved and access-checked
// independently, same as buildMailboxEmail/buildSenderEmail — so an alias can live on
// any domain the current admin/tenant controls, not just the mailbox's own domain.
func (a *App) aliasesList(w http.ResponseWriter, r *http.Request) {
	mailbox, ok := a.mailboxWithAccess(w, r)
	if !ok {
		return
	}
	aliases, err := a.DB.ListAliasesForMailbox(mailbox.ID)
	if err != nil {
		setFlash(w, "error", "Error loading aliases")
	}
	domains, _ := a.accessibleDomains(r)
	a.render(w, r, "mailbox_aliases.html", M{"active": "mailboxes", "mailbox": mailbox, "aliases": aliases, "domains": domains})
}

func (a *App) addAlias(w http.ResponseWriter, r *http.Request) {
	mailbox, ok := a.mailboxWithAccess(w, r)
	if !ok {
		return
	}
	localPart := strings.TrimSpace(r.FormValue("local_part"))
	domainID := int64(atoi(r.FormValue("domain_id")))
	canSendAs := r.FormValue("can_send_as") == "on"

	if !requireDomainAccess(w, r, domainID) {
		return
	}
	email, err := a.buildMailboxEmail(localPart, domainID)
	if err != nil {
		setFlash(w, "error", "Error creating alias")
		http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/aliases", http.StatusFound)
		return
	}
	if email == "" {
		setFlash(w, "error", "Please provide a valid local part (letters, numbers, and . _ % + - only) and domain")
		http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/aliases", http.StatusFound)
		return
	}
	if exists, _ := a.DB.MailboxEmailExists(email, -1); exists {
		setFlash(w, "error", "That address is already a mailbox")
		http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/aliases", http.StatusFound)
		return
	}
	if exists, _ := a.DB.AliasEmailExists(email, -1); exists {
		setFlash(w, "error", "That address is already an alias")
		http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/aliases", http.StatusFound)
		return
	}
	if _, err := a.DB.CreateAlias(mailbox.ID, email, domainID, canSendAs); err != nil {
		setFlash(w, "error", "Error creating alias")
		http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/aliases", http.StatusFound)
		return
	}
	setFlash(w, "success", "Alias added successfully")
	http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/aliases", http.StatusFound)
}

func (a *App) removeAlias(w http.ResponseWriter, r *http.Request) {
	mailbox, ok := a.mailboxWithAccess(w, r)
	if !ok {
		return
	}
	aliasID := int64(atoi(r.PathValue("alias_id")))
	if err := a.DB.RemoveAlias(aliasID, mailbox.ID); err != nil {
		setFlash(w, "error", "Error removing alias")
	} else {
		setFlash(w, "success", "Alias removed")
	}
	http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/aliases", http.StatusFound)
}
