package whatsapp

import (
	"context"
	"wechat-api/ent/predicate"
	"wechat-api/ent/whatsapp"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetAllowBlockListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetAllowBlockListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAllowBlockListLogic {
	return &GetAllowBlockListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetAllowBlockListLogic) GetAllowBlockList(req *types.IDReq) (resp *types.WhatsappAllowBlockListResp, err error) {
	isAdmin := l.ctx.Value("isAdmin").(bool)
	var predicates []predicate.Whatsapp
	predicates = append(predicates, whatsapp.IDEQ(req.Id))
	if !isAdmin {
		organizationId := l.ctx.Value("organizationId").(uint64)
		predicates = append(predicates, whatsapp.OrganizationID(organizationId))
	}
	whatsappInfo, err := l.svcCtx.DB.Whatsapp.Query().
		Where(predicates...).
		Only(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp = &types.WhatsappAllowBlockListResp{}
	resp.Data = types.WhatsappAllowBlockListRespData{}

	allowListData := ""
	if whatsappInfo.AllowList == nil || len(whatsappInfo.AllowList) == 0 || whatsappInfo.AllowList[0] == "ALL" {
		allowListData = "ALL"
	} else if len(whatsappInfo.AllowList) > 0 {
		for _, av := range whatsappInfo.AllowList {
			if av != "" {
				allowListData += av + "\n"
			}
		}
	}
	resp.Data.AllowList = &allowListData

	groupAllowListData := ""
	if whatsappInfo.GroupAllowList == nil || len(whatsappInfo.GroupAllowList) == 0 || whatsappInfo.GroupAllowList[0] == "ALL" {
		groupAllowListData = "ALL"
	} else if len(whatsappInfo.GroupAllowList) > 0 {
		for _, gav := range whatsappInfo.GroupAllowList {
			if gav != "" {
				groupAllowListData += gav + "\n"
			}
		}
	}
	resp.Data.GroupAllowList = &groupAllowListData

	blockListData := ""
	if whatsappInfo.BlockList != nil && len(whatsappInfo.BlockList) > 0 {
		if whatsappInfo.BlockList[0] == "ALL" {
			blockListData = "ALL"
		} else {
			for _, bv := range whatsappInfo.BlockList {
				if bv != "" {
					blockListData += bv + "\n"
				}
			}
		}
	}
	resp.Data.BlockList = &blockListData

	groupBlockListData := ""
	if whatsappInfo.GroupBlockList != nil && len(whatsappInfo.GroupBlockList) > 0 {
		if whatsappInfo.GroupBlockList[0] == "ALL" {
			groupBlockListData = "ALL"
		} else {
			for _, gbv := range whatsappInfo.GroupBlockList {
				if gbv != "" {
					groupBlockListData += gbv + "\n"
				}
			}
		}
	}
	resp.Data.GroupBlockList = &groupBlockListData
	return resp, nil
}
