package sql

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

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

type tagRepository struct {
	*BaseRepositoryImpl[domain.Tag]
	db     *gorm.DB
	tracer trace.Tracer
}

// NewTagRepository creates a new TagRepository.
func NewTagRepository(db *gorm.DB, cfg *config.Config) domain.TagRepository {
	return &tagRepository{
		BaseRepositoryImpl: NewBaseRepositoryImpl[domain.Tag](db, cfg),
		db:                 db,
		tracer:             otel.Tracer("tag.repository"),
	}
}

// FindByName finds a tag by name
func (r *tagRepository) FindByName(ctx context.Context, name string) (*domain.Tag, error) {
	ctx, span := r.tracer.Start(ctx, "FindByName")
	defer span.End()
	var tag domain.Tag
	if err := r.db.WithContext(ctx).Where("name = ?", name).First(&tag).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, domain.ErrEntityNotFound
		}
		return nil, err
	}
	return &tag, nil
}

// ListByWorkID finds tags by work ID
func (r *tagRepository) ListByWorkID(ctx context.Context, workID uint) ([]domain.Tag, error) {
	ctx, span := r.tracer.Start(ctx, "ListByWorkID")
	defer span.End()
	var tags []domain.Tag
	if err := r.db.WithContext(ctx).Joins("JOIN work_tags ON work_tags.tag_id = tags.id").
		Where("work_tags.work_id = ?", workID).
		Find(&tags).Error; err != nil {
		return nil, err
	}
	return tags, nil
}