package tools

import (
	"amocrm/internal/models"
	"fmt"
	"gitea.pena/SQuiz/common/model"
	"strings"
)

type ToUpdate struct {
	FieldID int
	Entity  model.EntityType
}

func ToCreatedUpdateQuestionRules(questionsTypeMap map[model.EntityType][]model.Question, currentFields []model.Field) (map[model.EntityType][]models.AddLeadsFields, map[int]ToUpdate) {
	toUpdate := make(map[int]ToUpdate) // на обновление ключ id вопроса значение id кастомного поля для тех у кого имя совпадает
	toCreated := make(map[model.EntityType][]models.AddLeadsFields)
	for entity, questions := range questionsTypeMap {
		for _, question := range questions {
			// если заголоввок пустой у вопроса делаем ему заголовок чтоб в амо легли филды нормально
			title := strings.ToLower(strings.ReplaceAll(question.Title, " ", ""))
			if title == "" {
				question.Title = fmt.Sprintf("Вопрос №%d", question.Page)
			}
			title = strings.ToLower(strings.ReplaceAll(question.Title, " ", ""))
			matched := false
			for _, field := range currentFields {
				fieldName := strings.ToLower(strings.ReplaceAll(field.Name, " ", ""))
				if title == fieldName && entity == field.Entity {
					toUpdate[int(question.Id)] = ToUpdate{
						FieldID: int(field.Amoid),
						Entity:  entity,
					}
					matched = true
					break
				}
			}

			if !matched {
				//Type: model.TypeMapping[question.Type]
				fieldType := model.TypeAmoTextarea
				if question.Type == model.TypeFile {
					fieldType = model.TypeAmoFile
				}
				toCreated[entity] = append(toCreated[entity], models.AddLeadsFields{Type: fieldType, Name: question.Title})
			}
		}
	}

	return toCreated, toUpdate
}

func ToQuestionIDs(rule map[int]int) []int32 {
	var ids []int32
	for queID, fieldID := range rule {
		if fieldID != 0 {
			continue
		}
		ids = append(ids, int32(queID))
	}
	return ids
}

func ForContactRules(quizConfig model.QuizContact, currentFields []model.Field) ([]models.AddLeadsFields, map[string]int) {
	var contactFieldsArr []model.ContactQuizConfig
	contactFieldTypes := map[model.ContactQuizConfig]bool{
		model.TypeContactName:    quizConfig.FormContact.Fields.Name.Used,
		model.TypeContactEmail:   quizConfig.FormContact.Fields.Email.Used,
		model.TypeContactPhone:   quizConfig.FormContact.Fields.Phone.Used,
		model.TypeContactText:    quizConfig.FormContact.Fields.Text.Used,
		model.TypeContactAddress: quizConfig.FormContact.Fields.Address.Used,
	}

	for fieldType, used := range contactFieldTypes {
		if used {
			contactFieldsArr = append(contactFieldsArr, fieldType)
		}
	}

	forAdding := make(map[string]int)
	var toCreated []models.AddLeadsFields
	for _, contactField := range contactFieldsArr {
		matched := false
		for _, field := range currentFields {
			if field.Name == string(contactField) && field.Entity == model.ContactsType {
				matched = true
				forAdding[string(contactField)] = int(field.Amoid)
				break
			}
		}

		if !matched {
			//Type: model.TypeMapping[question.Type]
			toCreated = append(toCreated, models.AddLeadsFields{Type: model.TypeAmoText, Name: string(contactField)})
			forAdding[string(contactField)] = 0
		}
	}

	return toCreated, forAdding
}
