package repository

import (
	"context"

	"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	"gorm.io/gorm"
)

type MarketingProductRepository interface {
	repository.BaseRepository[entity.MarketingProduct]
	GetByMarketingID(ctx context.Context, marketingID uint) ([]entity.MarketingProduct, error)
	IdExists(ctx context.Context, id uint) (bool, error)
}

type MarketingProductRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.MarketingProduct]
}

func NewMarketingProductRepository(db *gorm.DB) MarketingProductRepository {
	return &MarketingProductRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.MarketingProduct](db),
	}
}

func (r *MarketingProductRepositoryImpl) GetByMarketingID(ctx context.Context, marketingID uint) ([]entity.MarketingProduct, error) {
	var products []entity.MarketingProduct
	if err := r.DB().WithContext(ctx).
		Preload("ProductWarehouse.Product.Flags").
		Where("marketing_id = ?", marketingID).
		Find(&products).Error; err != nil {
		return nil, err
	}
	if len(products) == 0 {
		return products, gorm.ErrRecordNotFound
	}
	return products, nil
}

func (r *MarketingProductRepositoryImpl) IdExists(ctx context.Context, id uint) (bool, error) {
	return repository.Exists[entity.MarketingProduct](ctx, r.DB(), id)
}
