package novuhandler

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/pingcap/dbaas/billing2/forms"

	"github.com/pingcap/dbaas/billing2/config"

	"github.com/google/uuid"

	"github.com/pingcap/dbaas/billing2/utils/httpclient"
)

const (
	NovuInAPP = "in_app"
)
const (
	NovuParamOperator          = "_operator"
	NovuParamSource            = "_source"
	NovuParamSubject           = "_subject"
	NovuParamNotificationGroup = "_notificationGroup"
	NovuNotificationTitle      = "_notificationTitle"
	NovuSendAt                 = "sendAt"
	NovuIsSendNow              = "isSendNow"
	NovuTargetName             = "_targetName"
	NovuTargetRoles            = "_targetRoles"
	NovuTargetAllName          = "all"
)
const (
	CreateSubscriberSubscriberId = "subscriberId"
	CreateSubscriberLastName     = "lastName"
	CreateSubscriberFirstName    = "firstName"
	CreateSubscriberEmail        = "email"
)

type Env struct {
	Data []struct {
		Id             string `json:"_id"`
		Name           string `json:"name"`
		OrganizationId string `json:"_organizationId"`
		Identifier     string `json:"identifier"`
		ApiKeys        []struct {
			Key    string `json:"key"`
			UserId string `json:"_userId"`
		} `json:"apiKeys"`
		ParentId string `json:"_parentId"`
	} `json:"data"`
}

type NovuHandler interface {
	CreateWorkflow(flow forms.Workflow) (forms.Workflow, error)
	UpdateWorkflow(flow forms.Workflow) (forms.Workflow, error)
	DeleteWorkflow(flow forms.Workflow) error
	GetWorkflows(page int, pageSize int) (forms.WorkFlows, error)
	GetWorkflow(workflowID string) (forms.Workflow, error)
	DuplicateWorkflow(workflowID string) (forms.Workflow, error)
	BulkTriggerEvent(tenantID uint, trigger forms.Trigger) (forms.Workflow, error)
	BroadcastTriggerEvent(trigger forms.Trigger) (forms.Workflow, error)

	GetNotificationsByWorkflowID(query forms.NotificationQuery) (forms.OpsNotifications, error)
	GetNotificationsSummaryByWorkflowID(workflowID string) ([]forms.NotificationsSummary, error)
	GetNotificationGroupIDByName(name string) (string, error)
	GetNotificationGroupNameByID(id string) (string, error)
	GetNotificationsCount(subscriberID string, countType string) (int, error)

	GetSubscriberInAppNotifications(request forms.NotificationRequest) (forms.Notifications, error)
	GetSubscriberInAppNotificationByID(request forms.NotificationRequest) (forms.Notification, error)
	MarkMessagesAsSeen(request forms.NotificationMarkRequest) (bool, error)

	GetSubscriber(subscriberID string) (SubscriberInfo, bool)
	CreateSubscribers([]map[string]string) error
	DeleteSubscriber(subscriberID string) (bool, error)
}
type NovuHandlerImpl struct{}

var global NovuHandler = &NovuHandlerImpl{}

func Get() NovuHandler {
	return global
}

func Set(novuHandler NovuHandler) {
	global = novuHandler
}

func novuAuth(req *http.Request) error {
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", fmt.Sprintf("ApiKey %s", config.Get().GetString(config.NovuAPIKey)))
	req.Header.Set("Idempotency-Key", uuid.New().String())
	return nil
}

func GetClient() httpclient.HTTPClient {
	host := config.Get().GetString(config.NovuAPIHost)
	if !strings.HasPrefix(host, "http://") && !strings.HasPrefix(host, "https://") {
		host = "https://" + host
	}
	return httpclient.NewClient(novuAuth, host, "/")
}
