package com.walkguide.service;

import com.walkguide.dto.request.ObstacleLogRequest;
import com.walkguide.dto.response.ObstacleLogResponse;
import com.walkguide.entity.ObstacleLog;
import com.walkguide.entity.User;
import com.walkguide.enums.ActivityLogType;
import com.walkguide.repository.ObstacleLogRepository;
import com.walkguide.repository.UserRepository;
import com.walkguide.exception.ResourceNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ObstacleLogService {

    private final ObstacleLogRepository obstacleLogRepository;
    private final UserRepository userRepository;
    private final ActivityLogService activityLogService;

    public ObstacleLogResponse saveObstacle(Long userId, ObstacleLogRequest req) {
        ObstacleLog log = ObstacleLog.builder()
                .userId(userId)
                .label(req.getLabel())
                .confidence(req.getConfidence())
                .direction(req.getDirection())
                .estimatedDist(req.getEstimatedDist())
                .lat(req.getLat())
                .lng(req.getLng())
                .build();
        log = obstacleLogRepository.save(log);

        // Log ke activity_logs juga
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("User tidak ditemukan"));
        String meta = String.format("{\"label\":\"%s\",\"direction\":\"%s\",\"dist\":\"%s\",\"confidence\":%.2f}",
                req.getLabel(), req.getDirection(), req.getEstimatedDist(), req.getConfidence());
        activityLogService.createLog(user, ActivityLogType.OBSTACLE_DETECTED,
                "Obstacle terdeteksi: " + req.getLabel() + " (" + req.getDirection() + ")", meta);

        return toResponse(log);
    }

    public Page<ObstacleLogResponse> getObstacleLogs(Long userId, Pageable pageable) {
        return obstacleLogRepository.findByUserIdOrderByCreatedAtDesc(userId, pageable)
                .map(this::toResponse);
    }

    private ObstacleLogResponse toResponse(ObstacleLog l) {
        return ObstacleLogResponse.builder()
                .id(l.getId()).label(l.getLabel()).confidence(l.getConfidence())
                .direction(l.getDirection()).estimatedDist(l.getEstimatedDist())
                .lat(l.getLat()).lng(l.getLng()).createdAt(l.getCreatedAt()).build();
    }
}
