package whatsapp

import (
	"context"
	"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

		_, 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).
				SetNotNilCallback(req.Callback).
				SetNotNilAccount(req.Account).
				SetNotNilPhone(req.Phone).
				SetNotNilCc(req.Cc).
				SetNotNilPhoneName(req.PhoneName).
				SetNotNilPhoneStatus(req.PhoneStatus).
				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
}