package rules

import (
	"fmt"

	"code.tnxs.net/taxnexus/lib/api/devops/devops_client/user"
	"code.tnxs.net/taxnexus/lib/api/devops/devops_models"
	"code.tnxs.net/taxnexus/lib/api/workflow/workflow_client/outgoing_email_message"
	"code.tnxs.net/taxnexus/lib/api/workflow/workflow_models"
	"code.tnxs.net/taxnexus/lib/app"
	httptransport "github.com/go-openapi/runtime/client"
	"go.temporal.io/sdk/workflow"
)

// StoreAuth0UserActivity creates a new Auth0 user tied to a User record
func StoreAuth0UserActivity(ctx workflow.Context, w app.UserActivityWrapper) error { //nolint:gocritic // don't care
	auth0UserID, err := app.GetAuth0UserByEmail(w.Obj.Email)
	if err != nil {
		return err
	}
	if auth0UserID != "not found" {
		return fmt.Errorf("rules.StoreAuth0UserActivity: 💣 ⛔ Auth0 user exists: %s", auth0UserID)
	}
	newAuth0UserID, err := app.CreateNewAuth0User(&app.NewAuth0User{})
	if err != nil {
		return err
	}
	putUser := w.Obj
	putUser.Auth0UserID = newAuth0UserID
	//
	// update Taxnexus user
	//
	putUserParams := user.NewPutUsersParamsWithTimeout(getTimeout)
	putUserParams.UserRequest = &devops_models.UserRequest{
		Data: []*devops_models.User{&putUser},
	}
	_, err = devopsClient.User.PutUsers(putUserParams,
		httptransport.APIKeyAuth(
			"X-API-Key",
			"header",
			w.APIKey,
		))
	if err != nil {
		return err
	}
	//
	// send emails
	//
	emailParams := outgoing_email_message.NewPostOutgoingEmailMessagesParamsWithTimeout(postTimeout)
	emailParams.OutgoingEmailMessageRequest = &workflow_models.OutgoingEmailMessageRequest{
		Data: []*workflow_models.OutgoingEmailMessage{
			{
				Subject: putUser.ID,
			},
		},
	}
	_, err = workflowClient.
		OutgoingEmailMessage.
		PostOutgoingEmailMessages(
			emailParams,
			httptransport.APIKeyAuth(
				"X-API-Key",
				"header",
				w.APIKey,
			),
		)
	if err != nil {
		return err
	}
	return nil
}
