package department

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/department"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/predicate"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/hander"

	"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 GetDepartmentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetDepartmentLogic) GetDepartment(in *core.DepartmentReq) (*core.DepartmentInfo, error) {
	var predicates []predicate.Department
	if in.ID != 0 {
		predicates = append(predicates, department.IDEQ(in.ID))
		goto Query
	}
	if in.Name != "" {
		predicates = append(predicates, department.NameEQ(in.Name))
	}
	// 无条件不查询
	if len(predicates) == 0 {
		return nil, nil
	}
Query:
	query := l.svcCtx.DB.Department.Query().Where(predicates...)
	if in.WithUser {
		query.WithUsers()
	}
	if in.WithLeader {
		query.WithLeader()
	}
	if in.WithChildren {
		query.WithChildren()
	}
	dbData, err := query.First(l.ctx)
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}
	resp := l.svcCtx.Convert.ConvertDepartmentRpc(l.ctx, dbData)
	return resp, nil
}
