package main

import (
	"log"
	"os"
	"os/exec"

	"code.justin.tv/eventbus/client/testhelpers"
	"code.justin.tv/eventbus/schema/pkg/user"
	"code.justin.tv/live/autohost/internal/hosting/config"
)

const usage string = "USAGE: send-user-destroy <staging/production/customUrl>"
const environmentStaging = "staging"
const environmentProduction = "production"

// Sends a UserDestroy event bus event to the specified SQS queue. The terminal must have
// aws credentials before running this command.
//
// Examples:
//   Send a UserDestroy event to the staging environment
//   go run cmd/send-user-destroy/main.go staging
//
//
//   Send a UserDestroy event to the production environment
//   go run cmd/send-user-destroy/main.go production
//
//   Send a UserDestroy event to a custom sqs queue
//   go run cmd/send-user-destroy/main.go 'https://sqs.us-west-2.amazonaws.com/123456789/eventbus-test'
//
func main() {
	if len(os.Args) != 2 {
		log.Fatalf("ERROR: Invalid arguments.\n%s", usage)
	}

	var queueURLArg = os.Args[1]
	var queueURL string

	switch queueURLArg {
	case environmentStaging:
		queueURL = config.StagingConfig.EventBusQueueURL
	case environmentProduction:
		queueURL = config.ProductionConfig.EventBusQueueURL
	default:
		// If it's not the keywords above, assume a custom queue url was passed
		queueURL = queueURLArg
	}

	// Create the UserDestroy EventBus object
	message := &user.Destroy{
		UserId: "123",
		Login:  "FooUser",
	}

	raw, err := testhelpers.DefaultBinaryPayload(message)
	if err != nil {
		log.Fatal(err.Error())
	}

	snsMessage := raw.FakeSNSMessage()
	body, err := snsMessage.SQSBody()
	if err != nil {
		log.Fatal(err.Error())
	}

	// Execute the command
	log.Printf("Running command:\naws sqs send-message --queue-url '%s' --message-body '%s'\n\n", queueURL, body)
	cmd := exec.Command("aws", "sqs", "send-message", "--queue-url", queueURL, "--message-body", body)
	out, err := cmd.CombinedOutput()

	// Print the stdout/stderr of the aws command
	log.Println(string(out))

	if err != nil {
		log.Println(err.Error())
		return
	}
}
