package dictionary

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

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

func (l *GetDictionaryListLogic) GetDictionaryList(in *core.DictionaryReq) (*core.DictionaryListResp, error) {
	var predicates []predicate.Dictionary
	if in.Name != "" {
		predicates = append(predicates, dictionary.NameContains(in.Name))
	}
	if in.Title != "" {
		predicates = append(predicates, dictionary.TitleContains(in.Title))
	}

	query := l.svcCtx.DB.Dictionary.Query().Where(predicates...)
	if in.WithDetails {
		query.WithDetails()
	}
	var (
		pagination *core.Pagination
		list       []*ent.Dictionary
		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.DictionaryListResp{
		Page: pagination,
		Data: make([]*core.DictionaryInfo, len(list)),
	}

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