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) UpdateListUsers(ctx context.Context, accountID string) error {
	message := models.KafkaMessage{
		AccountID: accountID,
		Type:      models.UsersUpdate,
	}

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

	return nil
}

func (s *Service) GettingUserWithPagination(ctx context.Context, req *model.PaginationReq, accountID string) (*model.UserListResp, error) {
	response, err := s.repository.AmoRepo.GettingUserWithPagination(ctx, req, accountID)
	if err != nil {
		s.logger.Error("error getting users with pagination", zap.Error(err))
		return nil, err
	}
	return response, nil
}

func (s *Service) SoftDeleteAccount(ctx context.Context, accountID string) error {
	err := s.repository.AmoRepo.SoftDeleteAccount(ctx, accountID)
	if err != nil {
		s.logger.Error("error soft delete current account in softDeleteAccount service", zap.Error(err))
		return err
	}
	return nil
}

func (s *Service) GetCurrentAccount(ctx context.Context, accountID string) (*model.AmoAccount, error) {
	user, err := s.repository.AmoRepo.GetCurrentAccount(ctx, accountID)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, pj_errors.ErrNotFound
		}
		s.logger.Error("error getting current account in getCurrentAccount service", zap.Error(err))
		return nil, err
	}

	return user, nil
}

func (s *Service) ConnectAccount(ctx context.Context, accountID string) (*model.ConnectAccountResp, error) {
	link, err := s.socialAuthClient.GenerateAmocrmAuthURL(accountID)
	if err != nil {
		s.logger.Error("error sending request to pena social auth service:", zap.Error(err))
		return nil, err
	}

	response := model.ConnectAccountResp{
		Link: link,
	}

	return &response, nil
}
