package com.walkguide.service;

import com.walkguide.dto.response.DashboardResponse;
import com.walkguide.enums.PairingStatus;
import com.walkguide.exception.ResourceNotFoundException;
import com.walkguide.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class GuardianDashboardService {

    private final PairingRelationRepository pairingRelationRepository;
    private final LocationService locationService;
    private final ActivityLogService activityLogService;
    private final SosEventRepository sosEventRepository;
    private final GuardianNotificationRepository notifRepository;

    public DashboardResponse getDashboard(Long guardianId) {
        var pairing = pairingRelationRepository
                .findByGuardian_IdAndStatus(guardianId, PairingStatus.ACTIVE)
                .orElse(null);

        if (pairing == null) {
            return DashboardResponse.builder()
                    .recentActivity(java.util.List.of())
                    .unreadSosCount(0).unreadNotifCount(0).build();
        }

        var user = pairing.getUser();
        Long userId = user.getId();

        var lastLocation = locationService.getLastLocation(userId).orElse(null);
        var recentActivity = activityLogService.getLogs(userId, PageRequest.of(0, 5))
                .getContent();

        // Count unresolved SOS
        long unreadSos = sosEventRepository.findByUserIdOrderByCreatedAtDesc(userId, PageRequest.of(0, 100))
                .stream().filter(s -> s.getStatus().name().equals("TRIGGERED")).count();
        long unreadNotif = notifRepository.countByUserIdAndIsReadFalse(userId);

        return DashboardResponse.builder()
                .pairedUserId(userId)
                .pairedUserName(user.getDisplayName())
                .pairedUserEmail(user.getEmail())
                .uniqueUserId(user.getUniqueUserId())
                .lastLocation(lastLocation)
                .unreadSosCount(unreadSos)
                .unreadNotifCount(unreadNotif)
                .recentActivity(recentActivity)
                .build();
    }
}
