package district

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/svc"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/types/core"
	"git.noahlan.cn/noahlan/ntool/nstr"
)

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

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

func (l *GetDistrictNameLogic) GetDistrictName(in *core.GetDistrictNameReq) (*core.GetDistrictNameResp, error) {
	// cached data
	if cached, ok := getCachedDistrictItem(in.Code); ok {
		return &core.GetDistrictNameResp{
			Code:     cached.Code,
			Name:     nstr.JoinAny(in.Separator, cached.NameList),
			NameList: cached.NameList,
		}, nil
	}

	// get data
	// 获取当前code的所有父级列表
	listLogic := NewGetDistrictListLogic(l.ctx, l.svcCtx)
	dbData, err := listLogic.GetDistrictList(&core.DistrictReq{
		Code:      in.Code,
		QueryType: core.DistrictQueryType_Parents,
	})
	if err != nil {
		return nil, err
	}
	nameList := make([]string, len(dbData.Data))
	for i, item := range dbData.Data {
		nameList[i] = item.Name
	}

	// caching
	cacheDistrictItem(in.Code, nameList)

	return &core.GetDistrictNameResp{
		Code:     in.Code,
		Name:     nstr.JoinAny(in.Separator, nameList),
		NameList: nameList,
	}, nil
}
