package whatsapp

import (
	"context"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/whatsapp"
	"wechat-api/hook/aliyun"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

func (l *CreateWhatsappLogic) CreateWhatsapp(req *types.WhatsappInfo) (*types.BaseMsgResp, error) {
	add, err := aliyun.AddCamsPhoneNumber(*req.Phone, *req.Cc, *req.WaId, *req.PhoneName)
	l.Logger.Infof("add=%v err=%v\n", add, err)

	if err == nil && *add.Body.Code == "OK" {
		//var stringSlice []string

		phone := *req.Cc + *req.Phone
		callback := "https://wxadminapi-debug.gkscrm.com/webhook/whatsapp/receiveChatBotMsg"
		update, err := aliyun.UpdatePhoneWebhook(phone, *req.WaId, callback)
		l.Logger.Infof("updatePhone=%v  err=%v\n", update, err)

		if err != nil {
			return nil, errorx.NewInvalidArgumentError("修改号码回调失败")
		}

		_, err = l.svcCtx.DB.Whatsapp.Query().
			Where(whatsapp.WaID(*req.WaId)).
			Where(whatsapp.Phone(*req.Phone)).
			Where(whatsapp.Cc(*req.Cc)).
			First(l.ctx)
		if err != nil && ent.IsNotFound(err) {
			_, err = l.svcCtx.DB.Whatsapp.Create().
				SetNotNilWaID(req.WaId).
				SetNotNilWaName(req.WaName).
				SetNotNilCallback(req.Callback).
				SetNotNilAccount(req.Account).
				SetNotNilPhone(req.Phone).
				SetNotNilCc(req.Cc).
				SetCcPhone(*req.Cc + *req.Phone).
				SetNotNilPhoneName(req.PhoneName).
				SetNotNilOrganizationID(req.OrganizationId).
				//SetNotNilAgentID(req.AgentId).
				//SetNotNilAPIBase(req.ApiBase).
				//SetNotNilAPIKey(req.ApiKey).
				//SetNotNilAllowList(stringSlice).
				//SetNotNilGroupAllowList(stringSlice).
				//SetNotNilBlockList(stringSlice).
				//SetNotNilGroupBlockList(stringSlice).
				Save(l.ctx)

			if err != nil {
				return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
			}
			_ = l.svcCtx.Rds.Del(l.ctx, "wa_info")
		}
	}

	resp := types.BaseMsgResp{}
	if err != nil {
		resp.Msg = err.Error()
		resp.Code = 1
	} else {
		resp.Msg = "添加成功"
	}
	return &resp, nil
}
