package department

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/hander"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/msg"
	"git.noahlan.cn/noahlan/ntool-biz/core/orm/nent/types"

	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/svc"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/types/core"
)

type UpdateDepartmentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateDepartmentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateDepartmentLogic {
	return &UpdateDepartmentLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateDepartmentLogic) UpdateDepartment(in *core.DepartmentInfo) (*core.BaseResp, error) {
	update := l.svcCtx.DB.Department.Update()
	update.SetNotEmptyName(in.Name).
		SetNotEmptyRemark(in.Remark)
	if in.Status != "" {
		update.SetStatus(types.ParseStatus(in.Status))
	}
	if in.LeaderId != 0 {
		update.ClearLeader()
		update.SetLeaderID(in.LeaderId)
	}
	if in.ParentId != 0 {
		update.ClearParent()
		update.SetParentID(in.ParentId)
	}
	err := update.Exec(l.ctx)
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}

	return &core.BaseResp{
		Code: code.StatusOK,
		Msg:  msg.UpdateSuccess,
	}, nil
}
