package com.walkguide.service;

import com.walkguide.dto.request.HardwareShortcutUpdateRequest;
import com.walkguide.dto.response.HardwareShortcutResponse;
import com.walkguide.enums.HardwareShortcutKey;
import com.walkguide.exception.ResourceNotFoundException;
import com.walkguide.repository.HardwareShortcutRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class HardwareShortcutService {

    private final HardwareShortcutRepository hardwareShortcutRepository;

    public List<HardwareShortcutResponse> getAll(Long userId) {
        return hardwareShortcutRepository.findByUserId(userId).stream()
                .map(s -> HardwareShortcutResponse.builder()
                        .id(s.getId()).shortcutKey(s.getShortcutKey().name())
                        .buttonName(s.getButtonName()).buttonCode(s.getButtonCode())
                        .enabled(s.getEnabled()).build())
                .collect(Collectors.toList());
    }

    // Bisa dipanggil dari HP User langsung (capture button) atau dari Guardian
    public HardwareShortcutResponse update(Long userId, HardwareShortcutUpdateRequest req) {
        HardwareShortcutKey key = HardwareShortcutKey.valueOf(req.getShortcutKey());
        var shortcut = hardwareShortcutRepository.findByUserId(userId).stream()
                .filter(s -> s.getShortcutKey() == key)
                .findFirst()
                .orElseThrow(() -> new ResourceNotFoundException("Shortcut tidak ditemukan"));

        if (req.getButtonName() != null) shortcut.setButtonName(req.getButtonName());
        if (req.getButtonCode() != null) shortcut.setButtonCode(req.getButtonCode());
        if (req.getEnabled() != null)    shortcut.setEnabled(req.getEnabled());

        shortcut = hardwareShortcutRepository.save(shortcut);
        return HardwareShortcutResponse.builder()
                .id(shortcut.getId()).shortcutKey(shortcut.getShortcutKey().name())
                .buttonName(shortcut.getButtonName()).buttonCode(shortcut.getButtonCode())
                .enabled(shortcut.getEnabled()).build();
    }
}
