package com.walkguide.service;

import com.walkguide.dto.request.UserSettingsUpdateRequest;
import com.walkguide.dto.response.UserSettingsResponse;
import com.walkguide.entity.UserSettings;
import com.walkguide.repository.UserSettingsRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class UserSettingsService {

    private final UserSettingsRepository userSettingsRepository;

    public UserSettingsResponse getSettings(Long userId) {
        UserSettings s = userSettingsRepository.findByUserId(userId)
                .orElseGet(() -> userSettingsRepository.save(
                        UserSettings.builder().userId(userId).build()));
        return toResponse(s);
    }

    public UserSettingsResponse updateSettings(Long userId, UserSettingsUpdateRequest req) {
        UserSettings s = userSettingsRepository.findByUserId(userId)
                .orElseGet(() -> UserSettings.builder().userId(userId).build());

        if (req.getTtsLanguage() != null)    s.setTtsLanguage(req.getTtsLanguage());
        if (req.getTtsPitch() != null)       s.setTtsPitch(req.getTtsPitch());
        if (req.getTtsSpeed() != null)       s.setTtsSpeed(req.getTtsSpeed());
        if (req.getWarnNoGuardian() != null) s.setWarnNoGuardian(req.getWarnNoGuardian());
        if (req.getHapticEnabled() != null)  s.setHapticEnabled(req.getHapticEnabled());

        return toResponse(userSettingsRepository.save(s));
    }

    private UserSettingsResponse toResponse(UserSettings s) {
        return UserSettingsResponse.builder().id(s.getId())
                .ttsLanguage(s.getTtsLanguage()).ttsPitch(s.getTtsPitch())
                .ttsSpeed(s.getTtsSpeed()).warnNoGuardian(s.getWarnNoGuardian())
                .hapticEnabled(s.getHapticEnabled()).build();
    }
}
