package com.walkguide.service;

import com.walkguide.dto.request.AiConfigUpdateRequest;
import com.walkguide.dto.response.AiConfigResponse;
import com.walkguide.entity.AiConfig;
import com.walkguide.enums.PairingStatus;
import com.walkguide.exception.PairingException;
import com.walkguide.exception.ResourceNotFoundException;
import com.walkguide.repository.AiConfigRepository;
import com.walkguide.repository.PairingRelationRepository;
import com.walkguide.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AiConfigService {

    private final AiConfigRepository aiConfigRepository;
    private final PairingRelationRepository pairingRelationRepository;
    private final FcmService fcmService;

    public AiConfigResponse getConfig(Long userId) {
        AiConfig cfg = aiConfigRepository.findByUserId(userId)
                .orElseGet(() -> aiConfigRepository.save(AiConfig.builder().userId(userId).build()));
        return toResponse(cfg);
    }

    public AiConfigResponse updateConfigByGuardian(Long guardianId, AiConfigUpdateRequest req) {
        var pairing = pairingRelationRepository
                .findByGuardian_IdAndStatus(guardianId, PairingStatus.ACTIVE)
                .orElseThrow(() -> new PairingException("Tidak ada user yang dipair"));
        Long userId = pairing.getUser().getId();

        AiConfig cfg = aiConfigRepository.findByUserId(userId)
                .orElseGet(() -> aiConfigRepository.save(AiConfig.builder().userId(userId).guardianId(guardianId).build()));

        if (req.getConfidenceThreshold() != null) cfg.setConfidenceThreshold(req.getConfidenceThreshold());
        if (req.getAlertDistanceClose() != null)   cfg.setAlertDistanceClose(req.getAlertDistanceClose());
        if (req.getAlertDistanceMedium() != null)  cfg.setAlertDistanceMedium(req.getAlertDistanceMedium());
        if (req.getMaxInferenceFps() != null)       cfg.setMaxInferenceFps(req.getMaxInferenceFps());
        if (req.getEnabledLabels() != null)         cfg.setEnabledLabels(req.getEnabledLabels());

        cfg = aiConfigRepository.save(cfg);

        // Beritahu user settings telah diupdate
        String userFcm = pairing.getUser().getFcmToken();
        fcmService.sendToToken(userFcm, "Pengaturan AI Diperbarui",
                "Guardian mengubah konfigurasi deteksi AI",
                java.util.Map.of("type", "SETTINGS_UPDATED", "settingType", "AI_CONFIG"));

        return toResponse(cfg);
    }

    private AiConfigResponse toResponse(AiConfig c) {
        return AiConfigResponse.builder()
                .id(c.getId()).confidenceThreshold(c.getConfidenceThreshold())
                .alertDistanceClose(c.getAlertDistanceClose())
                .alertDistanceMedium(c.getAlertDistanceMedium())
                .maxInferenceFps(c.getMaxInferenceFps())
                .enabledLabels(c.getEnabledLabels()).build();
    }
}
