// # 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"
	"fmt"
	"log"
	"strings"

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

type User struct {
	XMLName   xml.Name `xml:"email-reminder_user"`
	FirstName string   `xml:"first_name,omitempty"`
	LastName  string   `xml:"last_name,omitempty"`
	Email     string   `xml:"email"`
	Events    []Event  `xml:"events>event,omitempty"`
}

func (u User) ToEmailRecipient() util.EmailRecipient {
	email := strings.TrimSpace(u.Email)
	if err := util.ValidateEmail(email); err != nil {
		log.Printf("Rejecting invalid email '%s': %s\n", email, err)
		email = ""
	}

	return util.EmailRecipient{Email: email, FirstName: strings.TrimSpace(u.FirstName), LastName: strings.TrimSpace(u.LastName)}
}

func LoadUserEvents(filename string, contents []byte, conf config.Config) (User, error) {
	v := User{}
	err := xml.Unmarshal(contents, &v)
	if err != nil {
		return v, fmt.Errorf("error parsing XML: %w", err)
	}
	if len(v.Events) > conf.MaxEventsPerUser {
		return v, fmt.Errorf("too many events (%d), maximum allowed is %d", len(v.Events), conf.MaxEventsPerUser)
	}
	return v, nil
}
