// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package repo

import (
	"net/http"
	"slices"
	"strings"

	repo_model "code.mokoconsulting.tech/MokoConsulting/MokoGitea/models/repo"
	user_model "code.mokoconsulting.tech/MokoConsulting/MokoGitea/models/user"
	shared_user "code.mokoconsulting.tech/MokoConsulting/MokoGitea/routers/web/shared/user"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/services/context"
)

type userSearchInfo struct {
	UserID     int64  `json:"user_id"`
	UserName   string `json:"username"`
	AvatarLink string `json:"avatar_link"`
	FullName   string `json:"full_name"`
}

type userSearchResponse struct {
	Results []*userSearchInfo `json:"results"`
}

func IssuePullPosters(ctx *context.Context) {
	isPullList := ctx.PathParam("type") == "pulls"
	issuePosters(ctx, isPullList)
}

func issuePosters(ctx *context.Context, isPullList bool) {
	repo := ctx.Repo.Repository
	search := strings.TrimSpace(ctx.FormString("q"))
	posters, err := repo_model.GetIssuePostersWithSearch(ctx, repo, isPullList, search)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, err)
		return
	}

	if search == "" && ctx.Doer != nil {
		// the returned posters slice only contains limited number of users,
		// to make the current user (doer) can quickly filter their own issues, always add doer to the posters slice
		if !slices.ContainsFunc(posters, func(user *user_model.User) bool { return user.ID == ctx.Doer.ID }) {
			posters = append(posters, ctx.Doer)
		}
	}

	posters = shared_user.MakeSelfOnTop(ctx.Doer, posters)

	resp := &userSearchResponse{}
	resp.Results = make([]*userSearchInfo, len(posters))
	for i, user := range posters {
		resp.Results[i] = &userSearchInfo{UserID: user.ID, UserName: user.Name, AvatarLink: user.AvatarLink(ctx)}
		resp.Results[i].FullName = user.FullName
	}
	ctx.JSON(http.StatusOK, resp)
}
