package com.walkguide.service;

import com.walkguide.dto.response.ActivityLogResponse;
import com.walkguide.entity.ActivityLog;
import com.walkguide.entity.User;
import com.walkguide.enums.ActivityLogType;
import com.walkguide.exception.ResourceNotFoundException;
import com.walkguide.repository.ActivityLogRepository;
import com.walkguide.repository.PairingRelationRepository;
import com.walkguide.enums.PairingStatus;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ActivityLogService {

    private final ActivityLogRepository activityLogRepository;
    private final PairingRelationRepository pairingRelationRepository;

    public void createLog(User user, ActivityLogType type, String description, String metadata) {
        ActivityLog log = ActivityLog.builder()
                .user(user)
                .logType(type)
                .description(description)
                .metadata(metadata)
                .build();
        activityLogRepository.save(log);
    }

    public Page<ActivityLogResponse> getLogs(Long userId, Pageable pageable) {
        return activityLogRepository
                .findByUser_IdOrderByCreatedAtDesc(userId, pageable)
                .map(this::toResponse);
    }

    public Page<ActivityLogResponse> getLogsForGuardian(Long guardianId, Pageable pageable) {
        var pairing = pairingRelationRepository
                .findByGuardian_IdAndStatus(guardianId, PairingStatus.ACTIVE)
                .orElseThrow(() -> new ResourceNotFoundException("Belum ada user yang dipair"));
        return activityLogRepository
                .findByUser_IdOrderByCreatedAtDesc(pairing.getUser().getId(), pageable)
                .map(this::toResponse);
    }

    private ActivityLogResponse toResponse(ActivityLog log) {
        return ActivityLogResponse.builder()
                .id(log.getId())
                .logType(log.getLogType().name())
                .description(log.getDescription())
                .metadata(log.getMetadata())
                .createdAt(log.getCreatedAt())
                .build();
    }
}
