// # Copyright (C) 2025 Francois Marier
//
// Email-Reminder is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 3 of the
// License, or (at your option) any later version.
//
// Email-Reminder is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Email-Reminder; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301, USA.
package events

import (
	"encoding/xml"
	"log"
	"strings"

	"launchpad.net/email-reminder/internal/util"
)

type Recipient struct {
	XMLName xml.Name `xml:"recipient"`
	Name    string   `xml:"name,attr,omitempty"`
	Email   string   `xml:"email,attr"`
}

// Splits Name into FirstName/LastName when needed
func (r Recipient) ToEmailRecipient() util.EmailRecipient {
	email := strings.TrimSpace(r.Email)
	if err := util.ValidateEmail(email); err != nil {
		log.Printf("Rejecting invalid email '%s': %s\n", email, err)
		email = ""
	}

	first := ""
	last := ""
	name := strings.TrimSpace(r.Name)
	if name != "" && len(name) < 255 { // ignore excessively long names
		parts := strings.Fields(name)
		if len(parts) > 0 {
			first = parts[0]
		}
		if len(parts) > 1 {
			last = strings.Join(parts[1:], " ")
		}
	}

	return util.EmailRecipient{Email: email, FirstName: first, LastName: last}
}
