package rules

import (
	"strconv"
	"strings"
	"time"

	"github.com/ultisuite/ulti-backend/internal/mail/webhooks"
)

func WebhookContextFromEvent(evt *EventContext, msg *Message) *webhooks.MessageContext {
	ctx := &webhooks.MessageContext{Date: time.Now().UTC().Format(time.RFC3339)}
	if msg != nil {
		senderName, senderEmail := parseFromAddress(msg.From)
		ctx.SenderName = senderName
		ctx.SenderEmail = senderEmail
		ctx.Subject = msg.Subject
		ctx.BodyText = msg.BodyText
		ctx.Recipients = strings.Join(msg.To, ", ")
		ctx.HasAttachment = msg.HasAttachments
		ctx.MessageID = msg.ID
	}
	if evt == nil {
		ctx.EventDomain = "mail"
		return ctx
	}
	ctx.EventType = string(evt.Type)
	ctx.EventDomain = webhookEventDomain(evt.Type)
	ctx.DriveFileName = evt.DriveFileName
	ctx.DriveFilePath = evt.DriveFilePath
	ctx.DriveMimeType = evt.DriveMimeType
	ctx.DriveFileSize = strconv.FormatInt(evt.DriveFileSize, 10)
	if evt.DriveIsFolder {
		ctx.DriveIsFolder = "true"
	} else {
		ctx.DriveIsFolder = "false"
	}
	ctx.ContactID = evt.ContactID
	ctx.ContactName = evt.ContactName
	ctx.ContactEmail = evt.ContactEmail
	ctx.ContactPhone = evt.ContactPhone
	ctx.ContactOrg = evt.ContactOrg
	return ctx
}

func webhookEventDomain(trigger TriggerType) string {
	switch trigger {
	case TriggerDriveFileCreated, TriggerDriveFileUpdated, TriggerDriveFileDeleted,
		TriggerDriveFileMoved, TriggerDriveShareUpdated:
		return "drive"
	case TriggerContactCreated, TriggerContactUpdated, TriggerContactDeleted:
		return "contacts"
	default:
		return "mail"
	}
}

func parseFromAddress(from string) (name, email string) {
	from = strings.TrimSpace(from)
	if from == "" {
		return "", ""
	}
	if i := strings.LastIndex(from, "<"); i >= 0 {
		j := strings.LastIndex(from, ">")
		if j > i {
			email = strings.TrimSpace(from[i+1 : j])
			name = strings.TrimSpace(from[:i])
			name = strings.Trim(name, `"`)
			return name, email
		}
	}
	return "", from
}
