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

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

func (l *GetDepartmentListLogic) GetDepartmentList(in *core.DepartmentReq) (*core.DepartmentListResp, 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.NameContains(in.Name))
	}
Query:
	query := l.svcCtx.DB.Department.Query().Where(predicates...)
	if in.WithUser {
		query.WithUsers()
	}
	if in.WithLeader {
		query.WithLeader()
	}
	if in.WithChildren {
		query.WithChildren()
	}
	var (
		pagination *core.Pagination
		list       []*ent.Department
		err        error
	)
	if in.Page != nil {
		result, pageErr := query.Page(l.ctx, in.Page.Current, in.Page.Size)
		if pageErr == nil {
			pagination = utils.ConvertPaginationDb(result.PageDetails)
			list = result.List
		} else {
			err = pageErr
		}
	} else {
		list, err = query.All(l.ctx)
	}
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}
	resp := &core.DepartmentListResp{
		Page: pagination,
		Data: make([]*core.DepartmentInfo, len(list)),
	}

	for i, v := range list {
		resp.Data[i] = l.svcCtx.Convert.ConvertDepartmentRpc(l.ctx, v)
	}
	return resp, nil
}
