package issues

import (
	"context"
	"time"

	"code.gitea.io/gitea/models/db"
	gitea_issues_models "code.gitea.io/gitea/models/issues"
	"code.gitlink.org.cn/Gitlink/gitea_hat.git/models/pull"
)

type PullRequestHatStatus int

// Enumerate all the pull request hat status
const (
	PullRequestHatStatusConflict PullRequestHatStatus = iota
	PullRequestHatStatusChecking
	PullRequestHatStatusMergeable
)

type PullRequest struct {
	gitea_issues_models.PullRequest
	LatestPullRequestVersion *pull.PullRequestVersion
}

func GetPullRequestIDsByIssueUpdatedUnix() ([]int64, error) {
	prs := make([]int64, 0, 10)
	return prs, db.GetEngine(db.DefaultContext).Table("pull_request").
		Where("issue.updated_unix>?", time.Now().Add(-time.Minute*2).Unix()).
		Join("INNER", "issue", "issue.id=pull_request.issue_id").
		Cols("pull_request.id").
		Find(&prs)
}

func (p *PullRequest) LoadLatestPullRequestVersion(ctx context.Context) (err error) {
	if p.LatestPullRequestVersion != nil {
		return nil
	}

	p.LatestPullRequestVersion, err = GetPullRequestLastVersionByPullRequest(ctx, p)

	return err
}

func GetPullRequestLastVersionByPullRequest(ctx context.Context, pr *PullRequest) (*pull.PullRequestVersion, error) {
	prv := &pull.PullRequestVersion{
		RepoID: pr.PullRequest.BaseRepoID,
		PullID: pr.PullRequest.ID,
	}
	has, err := db.GetEngine(ctx).Desc("created_unix").Get(prv)
	if err != nil {
		return nil, err
	} else if !has {
		return nil, gitea_issues_models.ErrPullRequestNotExist{}
	}

	return prv, nil
}
