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 userProfileRepository struct {
	*BaseRepositoryImpl[domain.UserProfile]
	db     *gorm.DB
	tracer trace.Tracer
}

// NewUserProfileRepository creates a new UserProfileRepository.
func NewUserProfileRepository(db *gorm.DB, cfg *config.Config) domain.UserProfileRepository {
	return &userProfileRepository{
		BaseRepositoryImpl: NewBaseRepositoryImpl[domain.UserProfile](db, cfg),
		db:                 db,
		tracer:             otel.Tracer("user_profile.repository"),
	}
}

// GetByUserID finds a user profile by user ID
func (r *userProfileRepository) GetByUserID(ctx context.Context, userID uint) (*domain.UserProfile, error) {
	ctx, span := r.tracer.Start(ctx, "GetByUserID")
	defer span.End()
	var profile domain.UserProfile
	if err := r.db.WithContext(ctx).Where("user_id = ?", userID).First(&profile).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, domain.ErrEntityNotFound
		}
		return nil, err
	}
	return &profile, nil
}