package github

import (
	"github.com/tidbcloud/devops/pkg/infra/clients/githubcli"
	"github.com/tidbcloud/devops/pkg/infra/config"
	"github.com/tidbcloud/devops/pkg/service"
	"github.com/tidbcloud/devops/pkg/service/github/repo"

	"github.com/tidbcloud/pkgv2/db"
	"go.uber.org/dig"
)

type ServiceParam struct {
	dig.In

	Github     *githubcli.GithubClient
	Conf       *config.RootConfig
	DBProvider db.TransProvider
}

type ServiceResult struct {
	dig.Out

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

type svc struct {
	*service.JobService

	conf config.GithubServiceConfig

	cli  *githubcli.GithubClient
	repo repo.Repo
	dbp  db.TransProvider
}

func NewService(p ServiceParam) (ServiceResult, error) {
	base := service.NewJobService("GithubService", service.WithDummy(p.Conf.Services.Github.Dummy))
	if p.Conf.Services.Github.Dummy {
		return ServiceResult{
			API:     &DummyGithubServiceAPI{},
			Service: base,
		}, nil
	}

	var err error
	s := &svc{
		JobService: base,
		conf:       p.Conf.Services.Github,
		cli:        p.Github,
		repo:       repo.NewRepo(p.DBProvider),
		dbp:        p.DBProvider,
	}

	if !s.conf.DisableSync {
		s.AddJob(
			service.NewConstantCronJob("SyncRepository", *s.conf.SyncRepositoryInterval, s.SyncRepository),
			service.NewConstantCronJob("SyncPullRequests", *s.conf.SyncPullRequestInterval, s.SyncPullRequests),
		)
	}

	return ServiceResult{API: s, Service: s}, err
}

func (s *svc) RawAPI() *githubcli.GithubClient {
	return s.cli
}
