package auditlog

import (
	"context"
	"time"

	"go.uber.org/zap"

	"github.com/tidbcloud/tiinf/transport/tieventbus"

	"github.com/tidbcloud/tiinf/monitor/tilog"
)

type OperatorType uint8
type OperatorLoginMethod string
type Result uint8
type EventType int
type ClusterType uint8

var eventbus tieventbus.Eventbus

// Event https://pingcap.feishu.cn/wiki/wikcnr6tbe0FQ9y96o24ZX8KDEd
type Event struct {
	Type                EventType    `json:"type"`
	EndsAt              time.Time    `json:"ends_at"`
	UserToken           string       `json:"user_token"`
	APIPubKey           string       `json:"api_pub_key"`
	AccessToken         string       `json:"access_token"`
	OperatorIP          string       `json:"operator_ip"`
	OrgID               uint64       `json:"org_id"`
	ProjectID           uint64       `json:"project_id"`
	ClusterID           uint64       `json:"cluster_id"`
	TraceID             string       `json:"trace_id"`
	Result              Result       `json:"result"`
	Details             string       `json:"details"`
	OperatorType        OperatorType `json:"operator_type"`
	OperatorID          uint64       `json:"operator_id"`
	OperatorEmail       string       `json:"operator_email"`
	OperatorLoginMethod string       `json:"operator_login_method"`
	OrgName             string       `json:"org_name"`
	ProjectName         string       `json:"project_name"`
	ClusterName         string       `json:"cluster_name"`
	ClusterType         ClusterType  `json:"cluster_type"`
}

func InitAuditLogSDK(ctx context.Context, timeout time.Duration) error {
	var err error
	eventbus, err = tieventbus.NewEventbus(tieventbus.EventbusConfig{
		AppName:   EventBusAppName,
		MQTimeout: timeout,
	})
	if err != nil {
		tilog.Error(ctx, "failed to init audit log sdk", zap.Error(err))
		return err
	}

	return eventbus.Run() //nolint:errcheck
}

func InitAuditLogSDKWithEventbus(ctx context.Context, externalEventbus tieventbus.Eventbus) error {
	eventbus = externalEventbus
	return nil
}

func InitMockAuditLogSDK(ctx context.Context, timeout time.Duration) error {
	var err error
	eventbus, err = tieventbus.NewEventbusMock(tieventbus.EventbusConfig{
		AppName:   EventBusAppName,
		MQTimeout: timeout,
	})
	if err != nil {
		tilog.Error(ctx, "failed to init audit log sdk", zap.Error(err))
		return err
	}

	return eventbus.Run() //nolint:errcheck
}
