package github

import (
	"context"
	"errors"

	"github.com/tidbcloud/ecosystem-service/internal/metric"
	"github.com/tidbcloud/tiinf/monitor/tilog"

	"go.uber.org/zap"
)

func (g *GitHubApp) HandleReRequestedCheckRun(ctx context.Context, checkRunEvent *GitHubCheckRunEvent) (err error) {
	tilog.Info(ctx, "handle event check run, action: rerequest")

	defer func() {
		if err != nil {
			metric.GitHubAppErrorCounter.WithLabelValues(metric.CheckRunEvent, "rerequest", metric.HandleCheckRun).Inc()
		}
	}()

	// filter check run
	if checkRunEvent.CheckRun.Name != checkName {
		return nil
	}

	// get externalID
	externalIDJson := checkRunEvent.CheckRun.ExternalID
	externalID, err := UnmarshalExternalID([]byte(externalIDJson))
	if err != nil {
		tilog.Error(ctx, "fail to unmarshal externalID", zap.String("externalID", externalIDJson), zap.Error(err))
		return err
	}

	// validate data
	if externalID.PullRequestBefore == nil {
		externalID.PullRequestBefore = Ptr("")
	}
	if externalID.PullRequestAction == nil {
		tilog.Error(ctx, "pull request action is empty")
		return nil
	}
	if len(checkRunEvent.CheckRun.PullRequests) == 0 {
		tilog.Error(ctx, "pull request is empty")
		return errors.New("pull request is empty")
	}

	// build pull request to reuse the HandlePullRequest
	pullRequestEvent := &GitHubPullRequestEvent{
		GitHubEvent: GitHubEvent{
			Installation: checkRunEvent.Installation,
			Action:       *externalID.PullRequestAction,
		},
		Number:       checkRunEvent.CheckRun.PullRequests[0].Number,
		Before:       *externalID.PullRequestBefore,
		Repository:   checkRunEvent.Repository,
		Organization: checkRunEvent.Organization,
		Sender:       checkRunEvent.Sender,
		PullRequest:  checkRunEvent.CheckRun.PullRequests[0],
	}

	// rerun
	return g.HandlePullRequest(ctx, pullRequestEvent, true)
}
