package department

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/entx"
	"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 CreateDepartmentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

// Role management
func (l *CreateDepartmentLogic) CreateDepartment(in *core.DepartmentInfo) (*core.BaseIDResp, error) {
	var id int64
	if err := entx.WithTx(l.ctx, l.svcCtx.DB, func(tx *ent.Tx) error {
		if err := l.preCheck(tx); err != nil {
			return err
		}
		create := tx.Department.Create().
			SetStatus(types.ParseStatus(in.Status)).
			SetName(in.Name).
			SetRemark(in.Remark)
		if in.LeaderId != 0 {
			create.SetLeaderID(in.LeaderId)
		}
		if in.ParentId != 0 {
			create.SetParentID(in.ParentId)
		}
		dbData, err := create.Save(l.ctx)
		if err != nil {
			return hander.HandleEntErr(err, in)
		}
		id = dbData.ID
		return nil
	}); err != nil {
		return nil, err
	}

	return &core.BaseIDResp{
		ID:   id,
		Code: code.StatusOK,
		Msg:  msg.CreateSuccess,
	}, nil
}

func (l *CreateDepartmentLogic) preCheck(tx *ent.Tx) error {
	return nil
}
