package handler

import (
	"context"

	"github.com/google/uuid"
	"github.com/tidbcloud/auditlog/consts"

	"github.com/tidbcloud/tiinf/errs"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"github.com/tidbcloud/tiinf/sdk/auditlog"
	"github.com/tidbcloud/tiinf/transport/tieventbus"
	"go.uber.org/zap"
	"gorm.io/gorm"

	"github.com/tidbcloud/auditlog/configs"
	"github.com/tidbcloud/auditlog/internal/dao"
	"github.com/tidbcloud/auditlog/internal/service"
	"github.com/tidbcloud/auditlog/third_party/account"
	"github.com/tidbcloud/auditlog/third_party/acl"
	"github.com/tidbcloud/auditlog/third_party/cluster_management"
)

var (
	auditSvc service.AuditSvc
)

func InitAuditService(ctx context.Context, cfg *configs.Config, db *gorm.DB, auditDao dao.AuditDaoIface) {
	accountSvc := account.NewAccountSvc(ctx, cfg)
	cmSvc := cluster_management.NewCMSvc(ctx, cfg)
	aclSvc := acl.NewAclSvcIface(ctx, cfg)

	auditSvc = service.NewAuditSvc(db, auditDao, accountSvc, cmSvc, aclSvc)
}

func ProcessAuditLog(event *tieventbus.Event) error {
	ctx := context.TODO()
	e, ok := event.Data.(*auditlog.Event)
	if !ok {
		tilog.Error(ctx, "invalid event type", zap.Any("event", event.Data))
		return errs.NewBadRequest("invalid event type", nil)
	}
	trace := uuid.New().String()
	tilog.Info(ctx, "handling event", zap.String("trace", trace), zap.String("eventID", event.ID), zap.Int("type", int(e.Type)), zap.String("type_name", consts.GetEventTypeName(e.Type)), zap.Uint64("orgID", e.OrgID), zap.Any("event", e))

	return auditSvc.CreateEvent(ctx, e, trace)
}
