package github

import (
	githubapi "github.com/tidbcloud/devops/api/github"
	ctrl "github.com/tidbcloud/devops/pkg/controller"
	"github.com/tidbcloud/devops/pkg/infra/clients/githubcli"
	ghsvc "github.com/tidbcloud/devops/pkg/service/github"

	"go.uber.org/dig"
)

type ControllerParam struct {
	dig.In

	GithubService ghsvc.GithubServiceAPI
}

type GithubController struct {
	svc ghsvc.GithubServiceAPI
}

func (c *GithubController) Name() string {
	return "GithubController"
}

func NewGithubController(p ControllerParam) ctrl.Controller {
	return &GithubController{
		svc: p.GithubService,
	}
}

func (c *GithubController) RegisterAPI(suite *ctrl.Suite) error {
	r := suite.Router
	g := r.Group("/github")
	{
		g.GET("/repos", c.ListRepositories)
		g.GET("/repos/:owner/:repo", c.GetRepo)

		g.GET("/pulls", c.ListPullRequests)
		g.GET("/pulls/:owner/:repo/:pr_number", c.GetPullRequest)

		raw := g.Group("/raw")
		{
			raw.GET("/repos/:owner/:repo/pulls", c.RawListPullRequests)
			raw.GET("/repos/:owner/:repo/pulls/:pr_number", c.RawGetPullRequest)

			raw.GET("/repos/:owner/:repo/releases", c.RawListReleases)
			raw.GET("/repos/:owner/:repo/releases/:release_tag", c.RawGetRelease)
			raw.GET("/repos/:owner/:repo/releases/diff", c.RawDiffRelease)

			raw.GET("/repos/:owner/:repo/labels", c.RawListLabels)
			raw.GET("/repos/:owner/:repo/labels/:label_name", c.RawGetLabel)
		}
	}

	ir := suite.InternalRouter
	irg := ir.Group("/github")
	{
		irg.POST("/repos/sync", c.SyncRepositories)
		irg.POST("/pulls/sync", c.SyncPullRequests)
	}

	return nil
}

func cvtPager(pager githubapi.CursorPagerReq) githubcli.Pager {
	return githubcli.Pager{
		PerPage: pager.PerPage,
		Cursor:  pager.Cursor,
	}
}

func cvtPagerResultToAPI(pager githubcli.PagerResult) githubapi.CursorPagerResp {
	return githubapi.CursorPagerResp{
		HasNextPage: pager.HasNextPage,
		EndCursor:   pager.EndCursor,
	}
}
