package service

import (
	"context"
	"errors"
	"time"

	"git.threesix.ai/jordan/slack5-1770541397/pkg/logging"
	"git.threesix.ai/jordan/slack5-1770541397/services/preferences-api/internal/domain"
	"git.threesix.ai/jordan/slack5-1770541397/services/preferences-api/internal/port"
)

// PreferencesService handles preference-related business logic.
type PreferencesService struct {
	repo   port.PreferencesRepository
	logger *logging.Logger
}

// NewPreferencesService creates a new preferences service.
func NewPreferencesService(repo port.PreferencesRepository, logger *logging.Logger) *PreferencesService {
	return &PreferencesService{
		repo:   repo,
		logger: logger.WithService("PreferencesService"),
	}
}

// GetPreferences returns the preferences for a user.
// If no preferences are stored, default preferences are returned.
func (s *PreferencesService) GetPreferences(ctx context.Context, userID domain.UserID) (*domain.UserPreferences, error) {
	prefs, err := s.repo.Get(ctx, userID)
	if err != nil {
		if errors.Is(err, domain.ErrPreferencesNotFound) {
			defaults := domain.DefaultPreferences()
			return &domain.UserPreferences{
				UserID:      userID,
				Preferences: defaults,
			}, nil
		}
		return nil, err
	}
	return prefs, nil
}

// SetPreferences validates and stores preferences for a user.
func (s *PreferencesService) SetPreferences(ctx context.Context, userID domain.UserID, prefs domain.Preferences) (*domain.UserPreferences, error) {
	if err := prefs.Validate(); err != nil {
		return nil, err
	}

	userPrefs := &domain.UserPreferences{
		UserID:      userID,
		Preferences: prefs,
		UpdatedAt:   time.Now().UTC(),
	}

	if err := s.repo.Upsert(ctx, userPrefs); err != nil {
		return nil, err
	}

	s.logger.Info("preferences updated", "user_id", string(userID))
	return userPrefs, nil
}
