package queue

import (
	"encoding/json"

	"github.com/aws/aws-sdk-go/service/sqs"
	"github.com/pkg/errors"

	"code.justin.tv/websocket-edge/server/internal/metrics"
	"code.justin.tv/websocket-edge/server/protocol"
)

type Queue interface {
	EmitDisconnectEvent(sessionID string) error
}

type sqsQueue struct {
	*sqs.SQS
	statter  metrics.Statter
	queueURL string
}

func NewSQSQueue(sqsClient *sqs.SQS, statter metrics.Statter, queueURL string) Queue {
	return &sqsQueue{
		SQS:      sqsClient,
		statter:  statter,
		queueURL: queueURL,
	}
}

func (s *sqsQueue) EmitDisconnectEvent(sessionID string) error {
	m := protocol.DisconnectMessage{
		SessionID: sessionID,
	}
	messageJSON, err := json.Marshal(m)
	if err != nil {
		return errors.Wrap(err, "unable to marshal disconnect message")
	}
	msg := string(messageJSON)

	input := &sqs.SendMessageInput{
		MessageBody: &msg,
		QueueUrl:    &s.queueURL,
	}
	_, err = s.SendMessage(input)
	if err != nil {
		return errors.Wrap(err, "unable to send disconect message top sqs")
	}
	return nil
}

// This is a simple No-op queue that satisfies the Queue interface.
type Noop struct{}

func (*Noop) EmitDisconnectEvent(sessionID string) error { return nil }
