package callee

import (
	"bytes"
	"encoding/json"
	"time"

	"code.justin.tv/sse/malachai/pkg/internal/discovery"
	"code.justin.tv/sse/malachai/pkg/jwtvalidation"
)

type snsMessage struct {
	Type              string                         `json:"Type"`
	MessageID         string                         `json:"MessageId"`
	TopicArn          string                         `json:"TopicArn"`
	Message           string                         `json:"Message"`
	Timestamp         time.Time                      `json:"Timestamp"`
	SignatureVersion  string                         `json:"SignatureVersion"`
	Signature         string                         `json:"Signature"`
	SigningCertURL    string                         `json:"SigningCertURL"`
	UnsubscribeURL    string                         `json:"UnsubscribeURL"`
	MessageAttributes map[string]snsMessageAttribute `json:"MessageAttributes"`
}

type snsMessageAttribute struct {
	Type  string
	Value string
}

func (e *eventsClient) handlePubkeyGenerationEvent(message string) (err error) {
	var key discovery.DynamoPublicKey
	err = json.NewDecoder(bytes.NewBufferString(message)).Decode(&key)
	if err != nil {
		return
	}

	select {
	case <-e.closer.Done():
	case e.pubkeyEvents <- &generatePubkeyEvent{key}:
	}
	return
}

func (e *eventsClient) handlePubkeyInvalidationEvent(message string) (err error) {
	caller := new(jwtvalidation.SigningEntity)
	err = json.NewDecoder(bytes.NewBufferString(message)).Decode(caller)
	if err != nil {
		return
	}

	select {
	case <-e.closer.Done():
	case e.pubkeyEvents <- &invalidatePubkeyEvent{caller}:
	}
	return
}

func (e *eventsClient) handleCapabilitiesEvent(message string) (err error) {
	select {
	case <-e.closer.Done():
	case e.capabilities <- struct{}{}:
	}
	return
}
