package gc.mda.kcg.domain.event;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class EventService {

    private final EventRepository repository;

    public List<EventDto> getByDateRange(Instant from, Instant to) {
        return repository.findByTimestampBetweenOrderByTimestampAsc(from, to)
                .stream().map(EventDto::from).toList();
    }

    public int importEvents(List<EventDto> dtos) {
        int count = 0;
        for (EventDto dto : dtos) {
            if (dto.getId() != null && repository.existsByEventId(dto.getId())) continue;
            Event e = Event.builder()
                    .eventId(dto.getId())
                    .title(dto.getLabel())
                    .description(dto.getDescription())
                    .source(dto.getSource())
                    .latitude(dto.getLat())
                    .longitude(dto.getLng())
                    .timestamp(Instant.ofEpochMilli(dto.getTimestamp()))
                    .rawData(Map.of(
                            "type", dto.getType() != null ? dto.getType() : "alert",
                            "intensity", dto.getIntensity() != null ? dto.getIntensity() : 50
                    ))
                    .build();
            repository.save(e);
            count++;
        }
        return count;
    }
}
