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 ProductCategoryRepository interface {
	repository.BaseRepository[entity.ProductCategory]
	NameExists(ctx context.Context, name string, excludeID *uint) (bool, error)
	CodeExists(ctx context.Context, code string, excludeID *uint) (bool, error)
}

type ProductCategoryRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.ProductCategory]
}

func NewProductCategoryRepository(db *gorm.DB) ProductCategoryRepository {
	return &ProductCategoryRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.ProductCategory](db),
	}
}

func (r *ProductCategoryRepositoryImpl) NameExists(ctx context.Context, name string, excludeID *uint) (bool, error) {
	return repository.ExistsByName[entity.ProductCategory](ctx, r.DB(), name, excludeID)
}

func (r *ProductCategoryRepositoryImpl) CodeExists(ctx context.Context, code string, excludeID *uint) (bool, error) {
	var count int64
	q := r.DB().WithContext(ctx).
		Model(new(entity.ProductCategory)).
		Where("code = ?", code).
		Where("deleted_at IS NULL")
	if excludeID != nil {
		q = q.Where("id <> ?", *excludeID)
	}
	if err := q.Count(&count).Error; err != nil {
		return false, err
	}
	return count > 0, nil
}
