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

type FlockRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.Flock]
	db *gorm.DB
}

func NewFlockRepository(db *gorm.DB) FlockRepository {
	return &FlockRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.Flock](db),
		db:                 db,
	}
}

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

func (r *FlockRepositoryImpl) GetByName(ctx context.Context, name string) (*entity.Flock, error) {
	var flock entity.Flock
	err := r.db.WithContext(ctx).
		Where("LOWER(name) = LOWER(?)", name).
		Where("deleted_at IS NULL").
		First(&flock).Error
	if err != nil {
		return nil, err
	}
	return &flock, nil
}
