package discovery

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/ultisuite/ulti-backend/internal/llm"
)

func (s *Service) GetLLMSettings(ctx context.Context, externalUserID string) (llm.Settings, error) {
	return s.loadLLMSettings(ctx, externalUserID)
}

func (s *Service) UpdateLLMSettings(ctx context.Context, externalUserID string, settings llm.Settings) (llm.Settings, error) {
	if s.db == nil {
		return llm.Settings{}, fmt.Errorf("database unavailable")
	}
	raw, err := json.Marshal(settings)
	if err != nil {
		return llm.Settings{}, err
	}
	_, err = s.db.Exec(ctx, `
		INSERT INTO settings (user_id, preferences)
		VALUES (
			(SELECT id FROM users WHERE external_id = $1),
			jsonb_build_object('llm', $2::jsonb)
		)
		ON CONFLICT (user_id) DO UPDATE SET
			preferences = jsonb_set(
				COALESCE(settings.preferences, '{}'::jsonb),
				'{llm}',
				$2::jsonb
			),
			updated_at = NOW()
	`, externalUserID, string(raw))
	if err != nil {
		return llm.Settings{}, err
	}
	return s.loadLLMSettings(ctx, externalUserID)
}

func LoadLLMSettingsFromPool(ctx context.Context, db *pgxpool.Pool, externalUserID string) (llm.Settings, error) {
	s := NewService(db)
	return s.loadLLMSettings(ctx, externalUserID)
}
