package service

import (
	"amocrm/internal/models"
	"context"
	"database/sql"
	"go.uber.org/zap"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/model"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/pj_errors"
)

func (s *Service) ChangeQuizSettings(ctx context.Context, request *model.RulesReq, accountID string, quizID int) error {
	err := s.repository.AmoRepo.ChangeQuizSettings(ctx, request, accountID, quizID)
	if err != nil {
		if err == sql.ErrNoRows {
			return pj_errors.ErrNotFound
		}
		s.logger.Error("error change quiz settings", zap.Error(err))
		return err
	}

	messageForUTM := models.KafkaMessage{
		AccountID: accountID,
		Type:      models.RuleCheck,
		Rule: models.KafkaRule{
			QuizID:      int32(quizID),
			PerformerID: request.PerformerID,
			PipelineID:  request.PipelineID,
			StepID:      request.StepID,
			Fieldsrule:  request.Fieldsrule,
		},
	}

	err = s.producer.ToKafkaUpdate(ctx, messageForUTM)
	if err != nil {
		s.logger.Error("error sending message to kafka for check rules", zap.Error(err))
		if err != nil {
			return err
		}
	}

	return nil
}

func (s *Service) SetQuizSettings(ctx context.Context, request *model.RulesReq, accountID string, quizID int) error {
	err := s.repository.AmoRepo.SetQuizSettings(ctx, request, accountID, quizID)
	if err != nil {
		if err == sql.ErrNoRows {
			return pj_errors.ErrNotFound
		}
		s.logger.Error("error setting quiz settings", zap.Error(err))
		return err
	}

	messageForUTM := models.KafkaMessage{
		AccountID: accountID,
		Type:      models.RuleCheck,
		Rule: models.KafkaRule{
			QuizID:      int32(quizID),
			PerformerID: request.PerformerID,
			PipelineID:  request.PipelineID,
			StepID:      request.StepID,
			Fieldsrule:  request.Fieldsrule,
		},
	}

	err = s.producer.ToKafkaUpdate(ctx, messageForUTM)
	if err != nil {
		s.logger.Error("error sending message to kafka for check rules", zap.Error(err))
		if err != nil {
			return err
		}
	}

	return nil
}

func (s *Service) GettingQuizRules(ctx context.Context, quizID int) (*model.Rule, error) {
	rule, err := s.repository.AmoRepo.GettingQuizRules(ctx, quizID)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, pj_errors.ErrNotFound
		}
		s.logger.Error("error getting quiz settings", zap.Error(err))
		return nil, err
	}
	return rule, nil
}
