package main

import (
	"context"
	"encoding/json"
	"errors"

	"code.justin.tv/live/backend-fundamentals/compute/logic"
	"code.justin.tv/live/backend-fundamentals/compute/schema"
	"github.com/aws/aws-lambda-go/lambda"
)

func main() {
	lambdaHandler := &primeLambdaHandler{
		logic: &logic.Logic{},
	}
	lambda.Start(lambdaHandler.handleRequest)
}

type primeRequest struct {
	Operation string                 `json:"operation"`
	Payload   map[string]interface{} `json:"payload"`
}

type primeLambdaHandler struct {
	logic *logic.Logic
}

func (p *primeLambdaHandler) handleRequest(_ context.Context, request primeRequest) (string, error) {
	rquestPayloadJson, err := json.Marshal(request.Payload)
	if err != nil {
		return "", err
	}

	switch request.Operation {
	case "isprime":
		return p.handleIsPrime(rquestPayloadJson)
	}

	return "", errors.New("unknown operation")
}

func (p *primeLambdaHandler) handleIsPrime(requestPayloadJson []byte) (string, error) {
	var isPrimeRequest schema.IsPrimeRequest
	err := json.Unmarshal(requestPayloadJson, &isPrimeRequest)
	if err != nil {
		return "", err
	}

	isPrimeResponse, err := p.logic.IsPrime(&isPrimeRequest)
	if err != nil {
		return "", err
	}

	responseBytes, err := json.Marshal(&isPrimeResponse)
	if err != nil {
		return "", err
	}

	return string(responseBytes), nil
}
