package com.walkguide.service;

import com.walkguide.dto.request.GeofenceConfigRequest;
import com.walkguide.dto.response.GeofenceResponse;
import com.walkguide.entity.GeofenceConfig;
import com.walkguide.enums.PairingStatus;
import com.walkguide.exception.PairingException;
import com.walkguide.repository.GeofenceConfigRepository;
import com.walkguide.repository.PairingRelationRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class GeofenceService {

    private final GeofenceConfigRepository geofenceConfigRepository;
    private final PairingRelationRepository pairingRelationRepository;

    public GeofenceResponse getConfig(Long userId) {
        return geofenceConfigRepository.findByUserId(userId)
                .map(this::toResponse)
                .orElse(GeofenceResponse.builder().enabled(false).radiusMeters(500.0).build());
    }

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

        GeofenceConfig cfg = geofenceConfigRepository.findByUserId(userId)
                .orElseGet(() -> GeofenceConfig.builder()
                        .userId(userId).guardianId(guardianId).build());

        if (req.getCenterLat() != null)   cfg.setCenterLat(req.getCenterLat());
        if (req.getCenterLng() != null)   cfg.setCenterLng(req.getCenterLng());
        if (req.getRadiusMeters() != null) cfg.setRadiusMeters(req.getRadiusMeters());
        if (req.getEnabled() != null)     cfg.setEnabled(req.getEnabled());

        return toResponse(geofenceConfigRepository.save(cfg));
    }

    private GeofenceResponse toResponse(GeofenceConfig c) {
        return GeofenceResponse.builder().id(c.getId())
                .centerLat(c.getCenterLat()).centerLng(c.getCenterLng())
                .radiusMeters(c.getRadiusMeters()).enabled(c.getEnabled()).build();
    }
}
