package main

import (
	"bytes"
	"context"
	"encoding/json"

	_ "github.com/go-sql-driver/mysql"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ssm"
)

// Response is of type APIGatewayProxyResponse since we're leveraging the
// AWS Lambda Proxy Request functionality (default behavior)
//
// https://serverless.com/framework/docs/providers/aws/events/apigateway/#lambda-proxy-integration
type Response events.APIGatewayProxyResponse

// Handler is our lambda handler invoked by the `lambda.Start` function call
func Handler(ctx context.Context) (Response, error) {
	svc := ssm.New(session.New(), &aws.Config{
		Region: aws.String("ap-northeast-1"),
	})
	res, _ := svc.GetParameter(&ssm.GetParameterInput{
		Name:           aws.String("db-endpoint"),
		WithDecryption: aws.Bool(true),
	})
	dbendpoint := *res.Parameter.Value

	/*
		res, _ = svc.GetParameter(&ssm.GetParameterInput{
			Name:           aws.String("db-username"),
			WithDecryption: aws.Bool(true),
		})
		dbusername := *res.Parameter.Value
			res, _ = svc.GetParameter(&ssm.GetParameterInput{
				Name:           aws.String("db-password"),
				WithDecryption: aws.Bool(true),
			})
			dbpassword := *res.Parameter.Value
	*/
	var buf bytes.Buffer

	body, err := json.Marshal(map[string]interface{}{
		"message":    "Okay so your other function also executed successfully!",
		"dbendpoint": dbendpoint,
	})
	if err != nil {
		return Response{StatusCode: 404}, err
	}
	json.HTMLEscape(&buf, body)

	resp := Response{
		StatusCode:      200,
		IsBase64Encoded: false,
		Body:            buf.String(),
		Headers: map[string]string{
			"Content-Type":           "application/json",
			"X-MyCompany-Func-Reply": "world-handler",
		},
	}

	return resp, nil
}

func main() {
	lambda.Start(Handler)
}
