package notifications

import (
	"encoding/json"

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

type TelegramReactionNotification struct {
	messaging.Envelope
	payload model.TelegramReactionRequest
}

func (trn *TelegramReactionNotification) Serialize() ([]byte, error) {
	data, err := json.Marshal(trn.payload)
	if err != nil {
		return nil, err
	}
	return trn.Wrap(data)
}

func telegramReactionEvent() model.NotificationEvent {
	return model.NewNotification(mservice.Notifications, nm.NATelegramReaction)
}

type TelegramTextNotification struct {
	messaging.Envelope
	payload model.TelegramTextRequest
}

func (ttn *TelegramTextNotification) Serialize() ([]byte, error) {
	data, err := json.Marshal(ttn.payload)
	if err != nil {
		return nil, err
	}
	return ttn.Wrap(data)
}

func telegramTextEvent() model.NotificationEvent {
	return model.NewNotification(mservice.Notifications, nm.NATelegramText)
}

type TelegramUpdateNotification struct {
	messaging.Envelope
	payload model.TelegramWebhookUpdate
}

func (tun *TelegramUpdateNotification) Serialize() ([]byte, error) {
	data, err := json.Marshal(tun.payload)
	if err != nil {
		return nil, err
	}
	return tun.Wrap(data)
}

func telegramUpdateEvent() model.NotificationEvent {
	return model.NewNotification(mservice.Notifications, nm.NATelegramUpdate)
}

func NewTelegramReactionEnvelope(sender string, request *model.TelegramReactionRequest) messaging.Envelope {
	var payload model.TelegramReactionRequest
	if request != nil {
		payload = *request
	}
	return &TelegramReactionNotification{
		Envelope: messaging.CreateEnvelope(sender, telegramReactionEvent()),
		payload:  payload,
	}
}

func NewTelegramTextEnvelope(sender string, request *model.TelegramTextRequest) messaging.Envelope {
	var payload model.TelegramTextRequest
	if request != nil {
		payload = *request
	}
	return &TelegramTextNotification{
		Envelope: messaging.CreateEnvelope(sender, telegramTextEvent()),
		payload:  payload,
	}
}

func NewTelegramUpdateEnvelope(sender string, update *model.TelegramWebhookUpdate) messaging.Envelope {
	var payload model.TelegramWebhookUpdate
	if update != nil {
		payload = *update
	}
	return &TelegramUpdateNotification{
		Envelope: messaging.CreateEnvelope(sender, telegramUpdateEvent()),
		payload:  payload,
	}
}
