package repository

import (
	"context"

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

type DocumentRepository interface {
	BaseRepository[entity.Document]
	ListByTarget(ctx context.Context, documentableType string, documentableID uint64, modifier func(*gorm.DB) *gorm.DB) ([]entity.Document, error)
	DeleteByTarget(ctx context.Context, documentableType string, documentableID uint64, modifier func(*gorm.DB) *gorm.DB) error
}

type documentRepositoryImpl struct {
	*BaseRepositoryImpl[entity.Document]
}

func NewDocumentRepository(db *gorm.DB) DocumentRepository {
	return &documentRepositoryImpl{
		BaseRepositoryImpl: NewBaseRepository[entity.Document](db),
	}
}

func (r *documentRepositoryImpl) ListByTarget(
	ctx context.Context,
	documentableType string,
	documentableID uint64,
	modifier func(*gorm.DB) *gorm.DB,
) ([]entity.Document, error) {
	var documents []entity.Document

	q := r.DB().WithContext(ctx).
		Where("documentable_type = ? AND documentable_id = ?", documentableType, documentableID)

	if modifier != nil {
		q = modifier(q)
	}

	if err := q.Order("created_at ASC").Find(&documents).Error; err != nil {
		return nil, err
	}

	return documents, nil
}

func (r *documentRepositoryImpl) DeleteByTarget(
	ctx context.Context,
	documentableType string,
	documentableID uint64,
	modifier func(*gorm.DB) *gorm.DB,
) error {
	q := r.DB().WithContext(ctx).
		Where("documentable_type = ? AND documentable_id = ?", documentableType, documentableID)

	if modifier != nil {
		q = modifier(q)
	}

	return q.Delete(&entity.Document{}).Error
}
