package internal

import (
	"strings"

	"github.com/tech/sendico/pkg/merrors"
	nm "github.com/tech/sendico/pkg/model/notification"
	"github.com/tech/sendico/pkg/mservice"
)

type NotificationEventImp struct {
	nType   mservice.Type
	nAction nm.NotificationAction
}

func (ne *NotificationEventImp) GetType() mservice.Type {
	return ne.nType
}

func (ne *NotificationEventImp) GetAction() nm.NotificationAction {
	return ne.nAction
}

const messageDelimiter string = "_"

func (ne *NotificationEventImp) Equals(other *NotificationEventImp) bool {
	return (other != nil) && (ne.nType == other.nType) && (ne.nAction == other.nAction)
}

func (ne *NotificationEventImp) ToString() string {
	return ne.StringType() + messageDelimiter + ne.StringAction()
}

func (ne *NotificationEventImp) StringType() string {
	return ne.nType
}

func (ne *NotificationEventImp) StringAction() string {
	return string(ne.nAction)
}

func NewNotificationImp(t mservice.Type, a nm.NotificationAction) *NotificationEventImp {
	return &NotificationEventImp{nType: t, nAction: a}
}

func FromStringImp(s string) (*NotificationEventImp, error) {
	parts := strings.Split(s, messageDelimiter)
	if len(parts) != 2 {
		return nil, merrors.Internal("invalid_notification_event_format")
	}

	res := &NotificationEventImp{}
	var err error
	if res.nType, err = mservice.StringToSType(parts[0]); err != nil {
		return nil, err
	}
	if res.nAction, err = StringToNotificationAction(parts[1]); err != nil {
		return nil, err
	}

	return res, nil
}

func StringToNotificationAction(s string) (nm.NotificationAction, error) {
	switch nm.NotificationAction(s) {
	case nm.NACreated, nm.NAPending, nm.NAUpdated, nm.NAArchived, nm.NADeleted, nm.NAAssigned, nm.NAPasswordReset, nm.NAConfirmationRequest, nm.NATelegramReaction, nm.NATelegramText, nm.NATelegramUpdate, nm.NAPaymentGatewayIntent, nm.NAPaymentGatewayExecution, nm.NADiscoveryServiceAnnounce, nm.NADiscoveryGatewayAnnounce, nm.NADiscoveryHeartbeat, nm.NADiscoveryLookupRequest, nm.NADiscoveryLookupResponse, nm.NADiscoveryRefreshUI:
		return nm.NotificationAction(s), nil
	default:
		return "", merrors.DataConflict("invalid Notification action: " + s)
	}
}

func StringToNotificationEventImp(eventType, eventAction string) (*NotificationEventImp, error) {
	et, err := mservice.StringToSType(eventType)
	if err != nil {
		return nil, err
	}
	ea, err := StringToNotificationAction(eventAction)
	if err != nil {
		return nil, err
	}
	return NewNotificationImp(et, ea), nil
}
