// Code generated by candi v1.3.1.

package graphqlhandler

import (
	"context"
	"errors"
	"time"

	"monorepo/services/notification-service/internal/modules/push-notif/domain"

	"pkg.agungdp.dev/candi/candishared"
	"pkg.agungdp.dev/candi/tracer"
)

type mutationResolver struct {
	root *GraphQLHandler
}

// Push resolver
func (m *mutationResolver) Push(ctx context.Context, input pushInputResolver) (string, error) {
	trace := tracer.StartTrace(ctx, "Delivery-Push")
	defer trace.Finish()

	ctx, tags := trace.Context(), trace.Tags()
	tags["input"] = input

	if err := m.root.uc.SendNotification(ctx, input.Payload); err != nil {
		return "", err
	}

	return "Ok", nil
}

// ScheduledNotification resolver
func (m *mutationResolver) ScheduledNotification(ctx context.Context, input scheduleNotifInputResolver) (string, error) {
	trace := tracer.StartTrace(ctx, "Delivery-ScheduledNotification")
	defer trace.Finish()

	ctx = trace.Context()

	scheduledAt, err := time.Parse(time.RFC3339, input.Payload.ScheduledAt)
	if err != nil {
		return "Failed parse scheduled time format", err
	}

	if scheduledAt.Before(time.Now()) {
		return "", errors.New("Scheduled time must in future")
	}

	if err := m.root.uc.SendScheduledNotification(ctx, scheduledAt, input.Payload.Data); err != nil {
		return "Failed set scheduled push notification", err
	}

	return "Success set scheduled push notification, scheduled at: " + input.Payload.ScheduledAt, nil
}

// ScheduledBroadcastEvent resolver
func (m *mutationResolver) ScheduledBroadcastEvent(ctx context.Context, input struct {
	ScheduledAt string
	Event       inputTopicEvent
}) (string, error) {
	trace := tracer.StartTrace(ctx, "Delivery-ScheduledBroadcastEvent")
	defer trace.Finish()
	// m.mw.GraphQLBasicAuth(ctx)

	ctx = trace.Context()

	scheduledAt, err := time.Parse(time.RFC3339, input.ScheduledAt)
	if err != nil {
		return "Failed parse scheduled time format", err
	}

	if scheduledAt.Before(time.Now()) {
		return "", errors.New("Scheduled time must in future")
	}

	if err := m.root.uc.SendScheduledEvent(ctx, scheduledAt, &domain.Event{
		ID: input.Event.ID, Message: input.Event.Message, Topic: input.Event.Topic,
	}); err != nil {
		return "Failed set scheduled event", err
	}

	return "Success set scheduled event, scheduled at: " + input.ScheduledAt, nil
}

func (m *mutationResolver) PublishMessageToTopic(ctx context.Context, input *inputTopicEvent) *domain.Event {

	tokenClaim := candishared.ParseTokenClaimFromContext(ctx)

	e := &domain.Event{Message: input.Message, Topic: input.Topic, ID: tokenClaim.Subject}
	e, _ = m.root.uc.PublishMessageToTopic(ctx, e)
	return e
}
