package department

import (
	"strconv"

	"github.com/gin-gonic/gin"

	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 DepartmentController struct {
	srv srvv1.Service
}

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

func (d *DepartmentController) Sync(c *gin.Context) {
	log.L(c).Info("DepartmentController.Sync controller function called.")

	ginres.WriteResponse(c, nil, "Start sync departments.")

	err := d.srv.Department().SyncWithLark(c)
	if err != nil {
		log.L(c).Error("Error when sync department with lark, err: " + err.Error())
	}
}

func (d *DepartmentController) List(c *gin.Context) {
	log.L(c).Info("DepartmentController.List controller function called.")

	params := ginres.ParseQuery(c, "pid", "excludes", "prec")
	if params["pid"] == "" {
		params["pid"] = "0"
	}
	prec, err := strconv.Atoi(params["prec"])
	if err != nil || prec <= 0 {
		prec = 3
	}

	res, err := d.srv.Department().List(c, params["pid"], params["excludes"], prec)
	if err != nil {
		ginres.WriteResponse(c, err, nil)

		return
	}

	ginres.WriteResponse(c, nil, res)
}
