package sql

import (
	"context"
	"tercul/internal/domain"
	"tercul/internal/platform/config"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/trace"
	"gorm.io/gorm"
)

type bookmarkRepository struct {
	domain.BaseRepository[domain.Bookmark]
	db     *gorm.DB
	tracer trace.Tracer
}

// NewBookmarkRepository creates a new BookmarkRepository.
func NewBookmarkRepository(db *gorm.DB, cfg *config.Config) domain.BookmarkRepository {
	return &bookmarkRepository{
		BaseRepository: NewBaseRepositoryImpl[domain.Bookmark](db, cfg),
		db:             db,
		tracer:         otel.Tracer("bookmark.repository"),
	}
}

// ListByUserID finds bookmarks by user ID
func (r *bookmarkRepository) ListByUserID(ctx context.Context, userID uint) ([]domain.Bookmark, error) {
	ctx, span := r.tracer.Start(ctx, "ListByUserID")
	defer span.End()
	var bookmarks []domain.Bookmark
	if err := r.db.WithContext(ctx).Where("user_id = ?", userID).Find(&bookmarks).Error; err != nil {
		return nil, err
	}
	return bookmarks, nil
}

// ListByWorkID finds bookmarks by work ID
func (r *bookmarkRepository) ListByWorkID(ctx context.Context, workID uint) ([]domain.Bookmark, error) {
	ctx, span := r.tracer.Start(ctx, "ListByWorkID")
	defer span.End()
	var bookmarks []domain.Bookmark
	if err := r.db.WithContext(ctx).Where("work_id = ?", workID).Find(&bookmarks).Error; err != nil {
		return nil, err
	}
	return bookmarks, nil
}
