package pdms

import (
	"context"
	"time"

	"code.justin.tv/live/autohost/internal/logfield"

	"code.justin.tv/amzn/PDMSLambdaTwirp"
	twirplambdatransport "code.justin.tv/amzn/TwirpGoLangAWSTransports/lambda"
	"code.justin.tv/creator-collab/log/errors"
	"code.justin.tv/live/autohost/internal/hosting/config"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/lambda"
	"github.com/golang/protobuf/ptypes/timestamp"
)

type Client interface {
	PromiseDeletion(ctx context.Context, userID string) error
}

type pdmsClientImpl struct {
	client PDMSLambdaTwirp.PDMSService
}

func CreateClient(pdmsRoleArn string, pdmsLambdaArn string, awsSession *session.Session) Client {
	creds := stscreds.NewCredentials(awsSession, pdmsRoleArn)
	svc := lambda.New(awsSession, &aws.Config{Credentials: creds})
	pdmsTransport := twirplambdatransport.NewClient(svc, pdmsLambdaArn)
	pdms := PDMSLambdaTwirp.NewPDMSServiceProtobufClient("", pdmsTransport)

	return &pdmsClientImpl{
		client: pdms,
	}
}

func (T *pdmsClientImpl) PromiseDeletion(ctx context.Context, userID string) error {
	// We promise PDMS that the user data will be purged in 90 days.
	_, err := T.client.PromiseDeletion(ctx, &PDMSLambdaTwirp.PromiseDeletionRequest{
		ServiceId:   config.AutohostTwitchServiceID,
		UserId:      userID,
		Timestamp:   &timestamp.Timestamp{Seconds: time.Now().AddDate(0, 0, 90).Unix()},
		AutoResolve: true,
	})

	if err != nil {
		return errors.Wrap(err, "PDMS client PromiseDelete failed", errors.Fields{
			logfield.UserID: userID,
		})
	}

	return err
}
