package search

import (
	"github.com/gin-gonic/gin"

	v1 "github.com/pingcap-inc/pchub/model/v1"

	"github.com/pingcap-inc/pchub/internal/pkg/code"
	"github.com/pingcap-inc/pchub/pkg/errors"

	srvv1 "github.com/pingcap-inc/pchub/internal/apiserver/service/v1"
	"github.com/pingcap-inc/pchub/internal/apiserver/store"
	"github.com/pingcap-inc/pchub/pkg/log"
	"github.com/pingcap-inc/pchub/pkg/util/ginres"
)

type SearchController struct {
	srv srvv1.Service
}

func NewSearchController(store store.Factory) *SearchController {
	return &SearchController{
		srv: srvv1.NewService(store),
	}
}

func (u *SearchController) SearchReceivers(c *gin.Context) {
	log.L(c).Info("SearchController.Search controller function called.")

	params := ginres.ParseQuery(c, "kw")
	if params["kw"] == "" {
		ginres.WriteResponse(c, nil, nil)

		return
	}

	ures, err1 := u.srv.User().Search(c, params["kw"])
	cres, err2 := u.srv.LarkChat().Search(c, params["kw"])
	if err1 != nil && err2 != nil {
		ginres.WriteResponse(c, errors.WithCode(code.ErrDatabase, ""), nil)

		return
	}

	res := make([]v1.AlertReceiver, 0)
	for _, u := range ures {
		n := u.EnName
		if n == "" {
			n = u.Name
		}
		res = append(res, v1.AlertReceiver{
			Type:   "user",
			Name:   n,
			Avatar: string(u.Avatars),
			LarkID: u.LarkUserID,
		})
	}
	for _, c := range cres {
		res = append(res, v1.AlertReceiver{
			Type:   "chat",
			Name:   c.Name,
			Avatar: c.Avatar,
			LarkID: c.ChatLarkID,
		})
	}

	ginres.WriteResponse(c, nil, res)
}
