package service

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

type ParamsWebhookCreate struct {
	Code       string // Authorization 20 минут
	Referer    string // адрес аккаунта пользователя
	AccountID  string // строка которая передавалась в соц аус сервисе
	FromWidget string
	Platform   string // ru/global  1/2
}

func (s *Service) WebhookCreate(ctx context.Context, req ParamsWebhookCreate) error {
	_, err := s.GetCurrentAccount(ctx, req.AccountID)
	if err != nil && !errors.Is(err, pj_errors.ErrNotFound) {
		s.logger.Error("error checking current account in amo in webhook create", zap.Error(err))
		return err
	}

	if errors.Is(err, pj_errors.ErrNotFound) {
		message := models.KafkaMessage{
			AccountID:  req.AccountID,
			AuthCode:   req.Code,
			RefererURL: req.Referer,
			Type:       models.UserCreate,
		}

		err = s.producer.ToKafkaUpdate(ctx, message)
		if err != nil {
			s.logger.Error("failed to send message to kafka on service webhook create", zap.Error(err))
			return err
		}
		return nil
	}

	message := models.KafkaMessage{
		AccountID:  req.AccountID,
		AuthCode:   req.Code,
		RefererURL: req.Referer,
		Type:       models.UserReLogin,
	}

	err = s.producer.ToKafkaUpdate(ctx, message)
	if err != nil {
		s.logger.Error("failed to send message to kafka on service webhook create, user re-login", zap.Error(err))
		return err
	}

	return nil
}

func (s *Service) WebhookDelete(ctx context.Context, amoID int) error {
	err := s.repository.AmoRepo.WebhookDelete(ctx, amoID)
	if err != nil {
		s.logger.Error("error canceled amo integration", zap.Error(err))
		return err
	}
	return nil
}
