package notify

import (
	"context"
	"fmt"

	"github.com/go-logr/logr"
	"github.com/tidbcloud/escalation-base/feishu_messager_v2/pkg/infra/clients/larkcli"
	larkmessage "github.com/tidbcloud/escalation-base/feishu_messager_v2/pkg/infra/clients/larkcli/message"
	"github.com/tidbcloud/escalation-base/feishu_messager_v2/pkg/infra/config"
	"github.com/tidbcloud/escalation-base/feishu_messager_v2/pkg/service"
	"go.uber.org/dig"
)

type ServiceParam struct {
	dig.In

	Conf          *config.RootConfig
	Logger        logr.Logger
	LarkClientSet *larkcli.LarkClientSet
}

type ServiceResult struct {
	dig.Out

	API     NotifyServiceAPI
	Service service.Service `group:"service"`
}

type svc struct {
	logger         logr.Logger
	larkClient     larkcli.LarkClient
	receiverChatId string
}

func NewService(p ServiceParam) (ServiceResult, error) {
	s := svc{
		logger:         p.Logger.WithName("NotifyService"),
		receiverChatId: p.Conf.Services.NotifyService.NotifyChatID,
	}

	clientKey := p.Conf.Services.NotifyService.NotifyClientKey
	larkcli, err := p.LarkClientSet.GetClient(clientKey)
	if err != nil {
		return ServiceResult{}, fmt.Errorf("larkclient not found for client_key %s: %w", clientKey, err)
	}
	s.larkClient = *larkcli

	return ServiceResult{API: &s, Service: &s}, nil
}

func (s *svc) Notify(ctx context.Context, message string) error {
	go s.notify(ctx, message)
	return nil
}

func (s *svc) notify(ctx context.Context, message string) error {
	_, err := s.larkClient.Message.SendMessage(
		ctx,
		"chat_id",
		s.receiverChatId,
		larkmessage.CardParam{
			Title: "feishu messager error",
			Text:  message,
		},
	)
	if err != nil {
		s.logger.Info("notify failed", "message", message, "error", err.Error())
	}
	return err
}

func (s *svc) Name() string {
	return "Notify"
}
