package post_deals_worker

import (
	"amocrm/internal/models"
	"amocrm/internal/repository"
	"amocrm/internal/tools"
	"amocrm/pkg/amoClient"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"go.uber.org/zap"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/dal"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/model"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/pj_errors"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/repository/amo"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/utils"
	"strconv"
	"strings"
	"time"
)

type Deps struct {
	AmoRepo   *dal.AmoDal
	AmoClient *amoClient.Amo
	RedisRepo *repository.Repository
	Logger    *zap.Logger
}

type PostDeals struct {
	amoRepo   *dal.AmoDal
	amoClient *amoClient.Amo
	redisRepo *repository.Repository
	logger    *zap.Logger
}

func NewPostDealsWC(deps Deps) *PostDeals {
	return &PostDeals{
		amoRepo:   deps.AmoRepo,
		amoClient: deps.AmoClient,
		redisRepo: deps.RedisRepo,
		logger:    deps.Logger,
	}
}

func (wc *PostDeals) Start(ctx context.Context) {
	ticker := time.NewTicker(1 * time.Minute)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			wc.startFetching(ctx)

		case <-ctx.Done():
			return
		}
	}
}

func (wc *PostDeals) startFetching(ctx context.Context) {
	results, err := wc.amoRepo.AmoRepo.GettingAmoUsersTrueResults(ctx)
	if err != nil {
		wc.logger.Error("error fetching users answers true results, for sending data to amo", zap.Error(err))
		return
	}

	mapDealReq := make(map[string][]models.DealReq)
	mapTokenDomain := make(map[string]string)

	for _, result := range results {
		userPrivileges, err := wc.amoRepo.AccountRepo.GetPrivilegesByAccountID(ctx, result.QuizAccountID)
		if err != nil {
			wc.logger.Error("error getting user privileges", zap.Error(err))
			return
		}

		if !utils.VerifyUserPrivileges(userPrivileges) {
			wc.logger.Info("User don't have active quizCnt or quizUnlim privileges, aborting")
			continue
		}

		allAnswers, err := wc.amoRepo.AnswerRepo.GetAllAnswersByQuizID(ctx, result.Session)
		if err != nil {
			wc.logger.Error("error getting all user answers by result session", zap.Error(err))
			return
		}
		userTags, err := wc.amoRepo.AmoRepo.GetUserTagsByID(ctx, result.AmoAccountID)
		if err != nil {
			wc.logger.Error("error getting user tags by ano account id", zap.Error(err))
			return
		}

		// За один запрос можно передать не более 50 сделок.
		deal := models.DealReq{
			Name:              fmt.Sprintf("deal quiz number %d", result.QuizID),
			StatusID:          result.StepID,
			PipelineID:        result.PipelineID,
			CreatedBy:         0, //result.AmoAccountID,
			UpdatedBy:         0,
			CreatedAt:         time.Now().Unix(),
			ResponsibleUserID: result.PerformerID,
			Embed: models.Embedd{
				Company: []models.Company{},
				Source: models.Source{
					Type: "widget",
				},
				Tags: tools.ConstructAmoTags(userTags, result.TagsToAdd),
			},
			// строка которая будет возвращенна в респонсе чтоб понимать кто есть что
			RequestID: strconv.Itoa(int(result.AnswerID)),
		}

		leadFields, contactData, companyData, customerToCreate, err := wc.constructField(ctx, allAnswers, result)
		if err != nil {
			wc.logger.Error("error construct fields", zap.Error(err))
			return
		}

		currentFields, err := wc.amoRepo.AmoRepo.GetUserFieldsByID(ctx, result.AmoAccountID)
		if err != nil {
			wc.logger.Error("error getting current user fields from db", zap.Error(err))
			return
		}

		utmFields := tools.ConstructUTMFields(result.UTMs, currentFields)

		_, err = wc.amoClient.CreatingCustomer(customerToCreate, result.AccessToken, result.SubDomain)
		if err != nil {
			wc.logger.Error("error sending requests for create customer", zap.Error(err))
			continue
		}

		err = wc.redisRepo.CachingLeadFieldsToRedis(ctx, result.AnswerID, leadFields)
		if err != nil {
			wc.logger.Error("error saving leads fields in redis", zap.Error(err))
			return
		}

		deal.Embed.Contact = contactData
		deal.Embed.Company = companyData
		deal.CustomFieldsValues = utmFields

		wc.logger.Info("NOW DEAL CONSTRUCTED IS:", zap.Any("DEAL", deal))

		if len(mapDealReq[result.AccessToken]) >= 49 {
			wc.logger.Info("reached maximum number of deals for access token", zap.String("access_token", result.AccessToken))
			err = wc.sendingDealsReq(ctx, mapDealReq, mapTokenDomain)
			if err != nil {
				wc.logger.Error("error sending requests for create deals", zap.Error(err))
				return
			}
			mapDealReq = make(map[string][]models.DealReq)
		}

		mapDealReq[result.AccessToken] = append(mapDealReq[result.AccessToken], deal)
		mapTokenDomain[result.AccessToken] = result.SubDomain
	}

	err = wc.sendingDealsReq(ctx, mapDealReq, mapTokenDomain)
	if err != nil {
		wc.logger.Error("error send requests for create deals", zap.Error(err))
		return
	}
}

func (wc *PostDeals) sendingDealsReq(ctx context.Context, mapDealReq map[string][]models.DealReq, mapTokenDomain map[string]string) error {
	for accessToken, deal := range mapDealReq {
		subDomain := mapTokenDomain[accessToken]
		resp, err := wc.amoClient.CreatingDeal(deal, accessToken, subDomain)
		if err != nil {
			// todo логирование в тг
			wc.logger.Error("error creating deal in amo", zap.Error(err))
			return err
		}
		err = wc.saveDealToDB(ctx, resp, accessToken, subDomain)
		if err != nil {
			wc.logger.Error("error saving resp data to db", zap.Error(err))
			return err
		}
	}
	return nil
}

func (wc *PostDeals) saveDealToDB(ctx context.Context, resp []models.DealResp, accessToken string, subDomain string) error {
	status := "pending"
	for _, dealResp := range resp {
		requestID := strings.Join(dealResp.RequestID, ",")
		answerID, err := strconv.ParseInt(requestID, 10, 64)
		if err != nil {
			wc.logger.Error("error converting str requestID to int answerID", zap.Error(err))
			return err
		}

		err = wc.amoRepo.AmoRepo.SaveDealAmoStatus(ctx, amo.SaveDealAmoDeps{DealID: dealResp.DealID, AnswerID: answerID, AccessToken: accessToken, Status: status})
		if err != nil {
			wc.logger.Error("error saving deal status to database", zap.Error(err))
			return err
		}

		err = wc.redisRepo.CachingDealToRedis(ctx, models.SaveDeal{
			AnswerID:    answerID,
			DealID:      dealResp.DealID,
			AccessToken: accessToken,
			SubDomain:   subDomain,
		})

		if err != nil {
			wc.logger.Error("error saving deal to redis", zap.Error(err))
			return err
		}
	}
	return nil
}

func (wc *PostDeals) constructField(ctx context.Context, allAnswers []model.ResultAnswer, result model.AmoUsersTrueResults) ([]models.FieldsValues, []models.Contact, []models.Company, []models.Customer, error) {
	dateCreating := time.Now().Unix()

	entityFieldsMap := make(map[model.EntityType]map[int][]models.ValueInterface)
	entityFieldsMap[model.LeadsType] = make(map[int][]models.ValueInterface)
	entityFieldsMap[model.CompaniesType] = make(map[int][]models.ValueInterface)
	entityFieldsMap[model.CustomersType] = make(map[int][]models.ValueInterface)

	entityRules := make(map[model.EntityType][]model.FieldRule)
	entityRules[model.LeadsType] = result.FieldsRule.Lead
	entityRules[model.CompaniesType] = result.FieldsRule.Company
	entityRules[model.CustomersType] = result.FieldsRule.Customer

	for entityType, ruleList := range entityRules {
		for _, rule := range ruleList {
			for _, data := range allAnswers {
				if fieldID, ok := rule.Questionid[int(data.QuestionID)]; ok {

					fieldData, err := wc.amoRepo.AmoRepo.GetFieldByID(ctx, int32(fieldID))
					if err != nil {
						return nil, nil, nil, nil, err
					}

					if fieldData.Type == model.TypeAmoText {
						values := entityFieldsMap[entityType][fieldID]
						content := strings.ReplaceAll(data.Content, " ", "")
						if content == "" {
							data.Content = "Пустая строка"
						}
						values = append(values, models.Values{Value: tools.EmojiUnicode(data.Content)})
						entityFieldsMap[entityType][fieldID] = values
						continue
					}

					if fieldData.Type == model.TypeFile && data.Content != "" && result.DriveURL != "" {
						value, err := wc.amoClient.UploadFileToAmo(data.Content, result.AccessToken, result.DriveURL)
						if err != nil {
							return nil, nil, nil, nil, err
						}
						values := entityFieldsMap[entityType][fieldID]
						values = append(values, value)
						entityFieldsMap[entityType][fieldID] = values
						continue
					}
				}
			}
		}
	}

	var leadFields []models.FieldsValues
	var contactFields []models.FieldsValues
	var companyFields []models.FieldsValues
	var customerFields []models.FieldsValues

	for entityType, fieldMap := range entityFieldsMap {
		for fieldID, values := range fieldMap {
			field := models.FieldsValues{
				FieldID: fieldID,
				Values:  values,
			}
			switch entityType {
			case model.LeadsType:
				leadFields = append(leadFields, field)
			case model.CompaniesType:
				companyFields = append(companyFields, field)
			case model.CustomersType:
				customerFields = append(customerFields, field)
			}
		}
	}

	var resultInfo model.ResultContent
	err := json.Unmarshal([]byte(result.Content), &resultInfo)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	var contactID int32
	contactRuleMap := result.FieldsRule.Contact.ContactRuleMap

	contactFields = tools.AddContactFields(contactFields, resultInfo.Name, model.TypeContactName, contactRuleMap)
	contactFields = tools.AddContactFields(contactFields, resultInfo.Phone, model.TypeContactPhone, contactRuleMap)
	contactFields = tools.AddContactFields(contactFields, resultInfo.Text, model.TypeContactText, contactRuleMap)
	contactFields = tools.AddContactFields(contactFields, resultInfo.Email, model.TypeContactEmail, contactRuleMap)
	contactFields = tools.AddContactFields(contactFields, resultInfo.Address, model.TypeContactAddress, contactRuleMap)

	name := resultInfo.Name
	if name == "" {
		name = fmt.Sprintf("empty name, quiz %d, triggered by answer - %d", result.QuizID, result.AnswerID)
	}

	var fields []string
	if resultInfo.Phone != "" {
		fields = append(fields, resultInfo.Phone)
	}

	if resultInfo.Email != "" {
		fields = append(fields, resultInfo.Email)
	}

	existContactData, err := wc.amoRepo.AmoRepo.GetExistingContactAmo(ctx, result.AmoAccountID, fields)
	if err != nil && !errors.Is(err, pj_errors.ErrNotFound) {
		return nil, nil, nil, nil, err
	}
	if errors.Is(err, pj_errors.ErrNotFound) || len(existContactData) == 0 {
		fmt.Println("NO CONTACT")
		contactResp, err := wc.amoClient.CreateContact([]models.CreateContactReq{
			{
				Name:               resultInfo.Name,
				ResponsibleUserID:  result.PerformerID,
				CreatedBy:          0,
				UpdatedBy:          0,
				CreatedAt:          dateCreating,
				CustomFieldsValues: contactFields,
			},
		}, result.SubDomain, result.AccessToken)
		if err != nil {
			return nil, nil, nil, nil, err
		}
		for _, c := range contactResp.Embedded.Contacts {
			contactID = c.ID
		}

		if resultInfo.Phone != "" {
			_, err = wc.amoRepo.AmoRepo.InsertContactAmo(ctx, model.ContactAmo{
				AccountID: result.AmoAccountID,
				AmoID:     contactID,
				Field:     resultInfo.Phone,
			})
			if err != nil {
				return nil, nil, nil, nil, err
			}
		}

		if resultInfo.Email != "" {
			_, err = wc.amoRepo.AmoRepo.InsertContactAmo(ctx, model.ContactAmo{
				AccountID: result.AmoAccountID,
				AmoID:     contactID,
				Field:     resultInfo.Email,
			})
			if err != nil {
				return nil, nil, nil, nil, err
			}
		}
	} else if existContactData != nil && len(existContactData) > 0 {
		contactID, err = wc.chooseAndCreateContact(ctx, result, resultInfo, existContactData, dateCreating, contactFields, contactRuleMap)
		if err != nil {
			return nil, nil, nil, nil, err
		}
	}

	return leadFields, []models.Contact{
			{
				ID: contactID,
				//Name:               name,
				//ResponsibleUserID:  result.PerformerID,
				//CreatedBy:          0,
				//UpdatedBy:          0,
				//CreatedAt:          dateCreating,
				//CustomFieldsValues: contactFields,
			},
		}, []models.Company{
			{
				Name:               fmt.Sprintf("Компания %d", result.AnswerID),
				ResponsibleUserID:  result.PerformerID,
				CreatedBy:          0,
				UpdatedBy:          0,
				CreatedAt:          dateCreating,
				CustomFieldsValues: companyFields,
			},
		}, []models.Customer{
			{
				// в амо имя покупателя не может быть пустым, надо как то с этим жить
				Name:              name,
				ResponsibleUserID: result.PerformerID,
				CreatedBy:         0,
				UpdatedBy:         0,
				CreatedAt:         dateCreating,
				CustomFields:      customerFields,
				RequestID:         fmt.Sprint(result.AnswerID),
			},
		}, nil
}

func (wc *PostDeals) chooseAndCreateContact(ctx context.Context, result model.AmoUsersTrueResults, resultInfo model.ResultContent, existingContacts map[int32][]model.ContactAmo, dateCreating int64, contactFields []models.FieldsValues, contactRuleMap map[string]int) (int32, error) {
	// 1 ищем контакт в котором совпадает и телефон и емайл
	if resultInfo.Phone != "" && resultInfo.Email != "" {
		phoneMatchedContacts := make(map[int32]bool)
		for _, contactVariants := range existingContacts {
			for _, contact := range contactVariants {
				if contact.Field == resultInfo.Phone {
					phoneMatchedContacts[contact.AmoID] = true
				}
			}
		}
		for _, contactVariants := range existingContacts {
			for _, contact := range contactVariants {
				if contact.Field == resultInfo.Email {
					if _, ok := phoneMatchedContacts[contact.AmoID]; ok {
						fmt.Println("нашлось телефон и емайл в бд, с одинаковым амоид", resultInfo.Name, resultInfo.Phone, resultInfo.Email)
						return contact.AmoID, nil
					}
				}
			}
		}

		var phoneContactID, emailContactID int32
		var phoneID int64 /*emailID*/
		for _, contactVariants := range existingContacts {
			for _, contact := range contactVariants {
				if contact.Field == resultInfo.Phone {
					phoneContactID = contact.AmoID
					phoneID = contact.ID
				}
				if contact.Field == resultInfo.Email {
					emailContactID = contact.AmoID
					//emailID = contact.ID
				}
			}
		}

		if phoneContactID != 0 && emailContactID != 0 && phoneContactID != emailContactID {
			fmt.Println("нашлось телефон и емайл в бд, но это пока разные контакты", resultInfo.Name, resultInfo.Phone, resultInfo.Email)
			// делаем обновление телефона там где уже есть email
			var valuePhone []models.FieldsValues
			valuePhone = tools.AddContactFields(valuePhone, resultInfo.Phone, model.TypeContactPhone, contactRuleMap)
			name := resultInfo.Name
			if name == "" {
				name = fmt.Sprintf("empty name, quiz %d, triggered by answer - %d", result.QuizID, result.AnswerID)
			}
			_, err := wc.amoClient.UpdateContact(models.CreateContactReq{
				Name:               name,
				UpdatedBy:          0,
				ResponsibleUserID:  result.PerformerID,
				CustomFieldsValues: valuePhone,
			}, result.SubDomain, result.AccessToken, emailContactID)
			if err != nil {
				return 0, err
			}

			err = wc.amoRepo.AmoRepo.UpdateAmoContact(ctx, phoneID, resultInfo.Phone, emailContactID)
			if err != nil {
				return 0, err
			}

			// todo пока без линковки
			//_, err = wc.amoClient.LinkedContactToContact([]models.LinkedContactReq{
			//	{
			//		ToEntityID:   emailContactID,
			//		ToEntityType: "contacts",
			//		//Metadata: struct {
			//		//	//CatalogID int  `json:"catalog_id"`
			//		//	//Quantity  int  `json:"quantity"`
			//		//	IsMain bool `json:"is_main"`
			//		//	//UpdatedBy int  `json:"updated_by"`
			//		//	//PriceID   int  `json:"price_id"`
			//		//}(struct {
			//		//	//CatalogID int
			//		//	//Quantity  int
			//		//	IsMain bool
			//		//	//UpdatedBy int
			//		//	//PriceID   int
			//		//}{IsMain: true}),
			//	},
			//}, result.SubDomain, result.AccessToken, phoneContactID)
			//if err != nil {
			//	return 0, err
			//}

			return emailContactID, nil
		}
	}

	// 2 ищем контакт только по телефону
	if resultInfo.Phone != "" {
		for _, contactVariants := range existingContacts {
			for _, contact := range contactVariants {
				if contact.Field == resultInfo.Phone {
					// нашли контакт по телефону
					emailExists := false
					for _, variant := range existingContacts[contact.AmoID] {
						if variant.Field != contact.Field {
							if variant.Field != "" {
								emailExists = true
								break
							}
						}
					}
					if !emailExists && resultInfo.Email != "" {
						// email пустой обновляем контакт добавляя email, если не пустой
						fmt.Println("нашлось телефон, емайл не пустой, а в бд пустой. обновляем контакт", resultInfo.Name, resultInfo.Phone, resultInfo.Email)
						var valueEmail []models.FieldsValues
						valueEmail = tools.AddContactFields(valueEmail, resultInfo.Email, model.TypeContactEmail, contactRuleMap)
						name := resultInfo.Name
						if name == "" {
							name = fmt.Sprintf("empty name, quiz %d, triggered by answer - %d", result.QuizID, result.AnswerID)
						}
						_, err := wc.amoClient.UpdateContact(models.CreateContactReq{
							Name:               name,
							UpdatedBy:          0,
							ResponsibleUserID:  result.PerformerID,
							CustomFieldsValues: valueEmail,
						}, result.SubDomain, result.AccessToken, contact.AmoID)
						if err != nil {
							return 0, err
						}
						_, err = wc.amoRepo.AmoRepo.InsertContactAmo(ctx, model.ContactAmo{
							AccountID: result.AmoAccountID,
							AmoID:     contact.AmoID,
							Field:     resultInfo.Email,
						})
						if err != nil {
							return 0, err
						}
						return contact.AmoID, nil
					}
					if emailExists && resultInfo.Email != "" {
						// email не пустой значит это новый контакт создаем если наш email тоже не пустой
						fmt.Println("нашлось телефон, емайл не пустой и в бд не пустой. создаем новый контакт", resultInfo.Name, resultInfo.Phone, resultInfo.Email)
						name := resultInfo.Name
						if name == "" {
							name = fmt.Sprintf("empty name, quiz %d, triggered by answer - %d", result.QuizID, result.AnswerID)
						}
						resp, err := wc.amoClient.CreateContact([]models.CreateContactReq{
							{
								Name:               name,
								ResponsibleUserID:  result.PerformerID,
								CreatedBy:          0,
								UpdatedBy:          0,
								CreatedAt:          dateCreating,
								CustomFieldsValues: contactFields,
							},
						}, result.SubDomain, result.AccessToken)
						if err != nil {
							return 0, err
						}
						var contactID int32
						for _, c := range resp.Embedded.Contacts {
							contactID = c.ID
						}

						_, err = wc.amoRepo.AmoRepo.InsertContactAmo(ctx, model.ContactAmo{
							AccountID: result.AmoAccountID,
							AmoID:     contactID,
							Field:     resultInfo.Phone,
						})
						if err != nil {
							return 0, err
						}

						_, err = wc.amoRepo.AmoRepo.InsertContactAmo(ctx, model.ContactAmo{
							AccountID: result.AmoAccountID,
							AmoID:     contactID,
							Field:     resultInfo.Email,
						})
						if err != nil {
							return 0, err
						}
						return contactID, nil
					}
					// если пустой то это нужный контакт возвращаем его id, так как если мейл пустой у нас но номер совпадает а в бд не пустой значит оно нам надо
					fmt.Println("нашлось телефон, емайл пустой возвращаем существующий контакт", resultInfo.Name, resultInfo.Phone, resultInfo.Email)
					return contact.AmoID, nil
				}
			}
		}
	}

	// 3 ищем контакт только по email
	if resultInfo.Email != "" {
		for _, contactVariants := range existingContacts {
			for _, contact := range contactVariants {
				if contact.Field == resultInfo.Email {
					// нашли контакт по email
					phoneExists := false
					for _, variant := range existingContacts[contact.AmoID] {
						if variant.Field != contact.Field {
							if variant.Field != "" {
								phoneExists = true
								break
							}
						}
					}
					if !phoneExists && resultInfo.Phone != "" {
						// телефон пустой обновляем контакт добавляя телефон, если не пустой
						fmt.Println("нашлось емайл, телефон не пустой, а в бд пустой. обновляем контакт", resultInfo.Name, resultInfo.Phone, resultInfo.Email)
						var valuePhone []models.FieldsValues
						valuePhone = tools.AddContactFields(valuePhone, resultInfo.Phone, model.TypeContactPhone, contactRuleMap)
						name := resultInfo.Name
						if name == "" {
							name = fmt.Sprintf("empty name, quiz %d, triggered by answer - %d", result.QuizID, result.AnswerID)
						}
						_, err := wc.amoClient.UpdateContact(models.CreateContactReq{
							Name:               name,
							UpdatedBy:          0,
							ResponsibleUserID:  result.PerformerID,
							CustomFieldsValues: valuePhone,
						}, result.SubDomain, result.AccessToken, contact.AmoID)
						if err != nil {
							return 0, err
						}
						_, err = wc.amoRepo.AmoRepo.InsertContactAmo(ctx, model.ContactAmo{
							AccountID: result.AmoAccountID,
							AmoID:     contact.AmoID,
							Field:     resultInfo.Phone,
						})
						if err != nil {
							return 0, err
						}
						return contact.AmoID, nil
					}
					if phoneExists && resultInfo.Phone != "" {
						// телефон не пустой значит это новый контакт создаем если наш телефон не пустой
						fmt.Println("нашлось емайл, телефон не пустой и в бд не пустой. создаем новый контакт", resultInfo.Name, resultInfo.Phone, resultInfo.Email)
						name := resultInfo.Name
						if name == "" {
							name = fmt.Sprintf("empty name, quiz %d, triggered by answer - %d", result.QuizID, result.AnswerID)
						}
						resp, err := wc.amoClient.CreateContact([]models.CreateContactReq{
							{
								Name:               name,
								ResponsibleUserID:  result.PerformerID,
								CreatedBy:          0,
								UpdatedBy:          0,
								CreatedAt:          dateCreating,
								CustomFieldsValues: contactFields,
							},
						}, result.SubDomain, result.AccessToken)
						if err != nil {
							return 0, err
						}
						var contactID int32
						for _, c := range resp.Embedded.Contacts {
							contactID = c.ID
						}

						_, err = wc.amoRepo.AmoRepo.InsertContactAmo(ctx, model.ContactAmo{
							AccountID: result.AmoAccountID,
							AmoID:     contactID,
							Field:     resultInfo.Phone,
						})
						if err != nil {
							return 0, err
						}

						_, err = wc.amoRepo.AmoRepo.InsertContactAmo(ctx, model.ContactAmo{
							AccountID: result.AmoAccountID,
							AmoID:     contactID,
							Field:     resultInfo.Email,
						})
						if err != nil {
							return 0, err
						}
						return contactID, nil
					}

					// если пустой то это нужный контакт возвращаем его id, так как если телефон пустой у нас но мейл совпадает а в бд не пустой значит оно нам надо
					fmt.Println("нашлось емайл, телефон пустой возвращаем существующий контакт", resultInfo.Name, resultInfo.Phone, resultInfo.Email)
					return contact.AmoID, nil
				}
			}
		}
	}

	fmt.Println("ничего не нашлось, создаем новый контакт", resultInfo.Name, resultInfo.Phone, resultInfo.Email)
	// если дошлю до сюда то это новый контакт с новым email and phone
	name := resultInfo.Name
	if name == "" {
		name = fmt.Sprintf("empty name, quiz %d, triggered by answer - %d", result.QuizID, result.AnswerID)
	}
	resp, err := wc.amoClient.CreateContact([]models.CreateContactReq{
		{
			Name:               name,
			ResponsibleUserID:  result.PerformerID,
			CreatedBy:          0,
			UpdatedBy:          0,
			CreatedAt:          dateCreating,
			CustomFieldsValues: contactFields,
		},
	}, result.SubDomain, result.AccessToken)
	if err != nil {
		return 0, err
	}
	var contactID int32
	for _, c := range resp.Embedded.Contacts {
		contactID = c.ID
	}
	if resultInfo.Phone != "" {
		_, err = wc.amoRepo.AmoRepo.InsertContactAmo(ctx, model.ContactAmo{
			AccountID: result.AmoAccountID,
			AmoID:     contactID,
			Field:     resultInfo.Phone,
		})
		if err != nil {
			return 0, err
		}
	}

	if resultInfo.Email != "" {
		_, err = wc.amoRepo.AmoRepo.InsertContactAmo(ctx, model.ContactAmo{
			AccountID: result.AmoAccountID,
			AmoID:     contactID,
			Field:     resultInfo.Email,
		})
		if err != nil {
			return 0, err
		}
	}
	return contactID, nil
}

func (wc *PostDeals) Stop(_ context.Context) error {
	return nil
}
