package history

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.uber.org/zap"
	"log"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/errors"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/fields"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
)

type GetHistories struct {
	Pagination *models.Pagination
	Type       *string
	UserID     string
}

func (receiver *GetHistories) BSON() bson.M {
	query := bson.M{
		fields.History.IsDeleted: false,
		fields.History.Type:      *receiver.Type,
		fields.History.UserID:    receiver.UserID,
	}

	return query
}

type historyRepository interface {
	CountAll(context.Context, *GetHistories) (int64, errors.Error)
	FindMany(context.Context, *GetHistories) ([]models.History, errors.Error)
	Insert(context.Context, *models.History) (*models.History, errors.Error)
	GetRecentTariffs(context.Context, string) ([]models.TariffID, errors.Error) // new
	GetHistoryByID(context.Context, string) (*models.ReportHistory, errors.Error)
	GetDocNumber(context.Context, string) (map[string]int, errors.Error)
	CalculateCustomerLTV(ctx context.Context, from, to int64) (int64, errors.Error)
}

type authClient interface {
	GetUser(ctx context.Context, userID string) (*models.User, errors.Error)
}

type verificationClient interface {
	GetVerification(ctx context.Context, userID string) (*models.Verification, errors.Error)
}

type temlategenClient interface {
	SendData(ctx context.Context, data models.RespGeneratorService, fileContents []byte, email string) errors.Error
}

type Deps struct {
	Logger             *zap.Logger
	Repository         historyRepository
	AuthClient         authClient
	VerificationClient verificationClient
	TemlategenClient   temlategenClient
}

type Service struct {
	logger             *zap.Logger
	repository         historyRepository
	AuthClient         authClient
	VerificationClient verificationClient
	TemlategenClient   temlategenClient
}

func New(deps Deps) *Service {
	if deps.Logger == nil {
		log.Panicln("logger is nil on <New (history service)>")
	}

	if deps.Repository == nil {
		log.Panicln("repository is nil on <New (history service)>")
	}

	if deps.AuthClient == nil {
		log.Panicln("auth client is nil on <New (account service)>")
	}

	return &Service{
		logger:     deps.Logger,
		repository: deps.Repository,
		AuthClient: deps.AuthClient,
	}
}

func (receiver *Service) CreateHistory(ctx context.Context, history *models.History) (*models.History, errors.Error) {
	createdHistory, err := receiver.repository.Insert(ctx, history)
	if err != nil {
		receiver.logger.Error("failed to create history on <CreateHistory> of <HistoryService>", zap.Error(err))
		return nil, err
	}

	return createdHistory, nil
}
