package webui

import (
	"net/http"
	"strings"

	"mailgoserver/internal/db"
)

// webmailSignaturesPage lists a mailbox's saved signatures and the add/edit form.
func (a *App) webmailSignaturesPage(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	signatures, err := a.DB.ListSignatures(mbox.ID)
	if err != nil {
		setFlash(w, "error", "Error loading signatures")
	}

	// ?edit=<id> loads an existing signature into the form instead of a blank one.
	var editing *db.MailboxSignature
	if idStr := r.URL.Query().Get("edit"); idStr != "" {
		editing, _ = a.DB.GetSignatureByID(mbox.ID, int64(atoi(idStr)))
	}

	a.render(w, r, "webmail_signatures.html", M{
		"mailbox": mbox, "signatures": signatures, "editing": editing,
		"flashes": popFlashes(w, r),
	})
}

// webmailSignatureSave creates a new signature, or updates one when id (a hidden
// form field, not a path segment — this is a single form reused for add and edit) is
// set.
func (a *App) webmailSignatureSave(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	if err := r.ParseForm(); err != nil {
		setFlash(w, "error", "Invalid form data")
		http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
		return
	}
	name := strings.TrimSpace(r.FormValue("name"))
	contentHTML := r.FormValue("content_html")
	if name == "" {
		setFlash(w, "error", "Give the signature a name")
		http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
		return
	}

	id := int64(atoi(r.FormValue("id")))
	var err error
	if id != 0 {
		err = a.DB.UpdateSignature(mbox.ID, id, name, contentHTML)
	} else {
		_, err = a.DB.CreateSignature(mbox.ID, name, contentHTML)
	}
	if err != nil {
		a.Logger.Error("save signature for mailbox %d: %v", mbox.ID, err)
		setFlash(w, "error", "Could not save the signature")
	} else {
		setFlash(w, "success", "Signature saved")
	}
	http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
}

func (a *App) webmailSignatureDelete(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	id := int64(atoi(r.PathValue("id")))
	if err := a.DB.DeleteSignature(mbox.ID, id); err != nil {
		setFlash(w, "error", "Could not delete the signature")
	} else {
		setFlash(w, "success", "Signature deleted")
	}
	http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
}

// webmailSignatureSetDefault marks a signature (or, when id=0, clears the flag
// entirely) as the mailbox's default for new messages or for reply/forward, per the
// "which" form field ("new" or "reply").
func (a *App) webmailSignatureSetDefault(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	id := int64(atoi(r.PathValue("id")))
	forReply := r.URL.Query().Get("which") == "reply"
	if err := a.DB.SetDefaultSignature(mbox.ID, id, forReply); err != nil {
		setFlash(w, "error", "Could not update the default signature")
	} else {
		setFlash(w, "success", "Default signature updated")
	}
	http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
}
