package sscnotifications

import (
	"bytes"
	"context"
	"os"

	"github.com/PagerDuty/go-pagerduty"
	"github.com/golang/protobuf/jsonpb"
	securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1"
)

var pdAuthKey = os.Getenv("PAGERDUTY_API_KEY")

type PubSubMessage struct {
	Data []byte `json:"data"`
}

func NewEvent(finding *securitycenterpb.Finding) pagerduty.V2Event{
	return pagerduty.V2Event{
		RoutingKey: pdAuthKey,
		Action:     "trigger",
		DedupKey:   "gcp-scc-notification",
		Payload:    &pagerduty.V2Payload{
			Summary:   "FIRING:1",
			Source:    "GCP Security Command Center",
			Severity:  "critical",
			Details:   finding,
		},
	}
}

func ConsumePubSubMessage(ctx context.Context, m PubSubMessage) error {
	var notificationMessage = new(securitycenterpb.NotificationMessage)
	if unMarshalErr := jsonpb.Unmarshal(bytes.NewReader(m.Data), notificationMessage); unMarshalErr != nil {
		return unMarshalErr
	}
	event := NewEvent(notificationMessage.GetFinding())
	if _, eventErr := pagerduty.ManageEvent(event); eventErr != nil {
		return eventErr
	}
	return nil
}
