package com.example.demo.repository.impl;

import com.example.demo.model.Event;
import com.example.demo.model.enums.EventStatus;
import com.example.demo.repository.EventRepository;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 事件仓储内存实现。
 * <p>
 * 使用 ConcurrentHashMap 模拟数据库存储，应用启动时初始化示例数据。
 * 后续可替换为 MyBatis/JPA 等数据库实现。
 * </p>
 *
 * @requirement(name="事件存储与状态管理", id="SRS-EHTG-03")
 * 将处理后的事件存入内存存储，并维护其生命周期状态。
 */
@Repository
public class InMemoryEventRepository implements EventRepository {

    private final ConcurrentHashMap<String, Event> store = new ConcurrentHashMap<>();
    private final AtomicLong idCounter = new AtomicLong(0);

    public InMemoryEventRepository() {
        initSampleData();
    }

    /**
     * 初始化示例事件数据。
     */
    private void initSampleData() {
        LocalDateTime now = LocalDateTime.now();

        save(new Event("EVT-001", com.example.demo.model.enums.EventSourceType.RADAR,
                now.minusMinutes(30), "{\"lng\": 116.397, \"lat\": 39.908}", 0.95,
                EventStatus.PENDING, com.example.demo.model.enums.ThreatLevel.HIGH, "临机"));

        save(new Event("EVT-002", com.example.demo.model.enums.EventSourceType.OPTOELECTRONIC,
                now.minusMinutes(20), "{\"lng\": 121.473, \"lat\": 31.230}", 0.87,
                EventStatus.PENDING, com.example.demo.model.enums.ThreatLevel.CRITICAL, "临机"));

        save(new Event("EVT-003", com.example.demo.model.enums.EventSourceType.RADAR,
                now.minusMinutes(15), "{\"lng\": 113.264, \"lat\": 23.129}", 0.72,
                EventStatus.COMPLETED, com.example.demo.model.enums.ThreatLevel.MEDIUM, "规划"));

        save(new Event("EVT-004", com.example.demo.model.enums.EventSourceType.ELECTRONIC_RECON,
                now.minusMinutes(10), "{\"lng\": 114.057, \"lat\": 22.543}", 0.65,
                EventStatus.PENDING, com.example.demo.model.enums.ThreatLevel.LOW, "规划"));

        save(new Event("EVT-005", com.example.demo.model.enums.EventSourceType.COMMUNICATION_INTEL,
                now.minusMinutes(5), "{\"lng\": 120.155, \"lat\": 30.274}", 0.91,
                EventStatus.PROCESSING, com.example.demo.model.enums.ThreatLevel.HIGH, "临机"));
    }

    @Override
    public Event save(Event event) {
        if (event.getEventId() == null || event.getEventId().isEmpty()) {
            String id = "EVT-" + String.format("%03d", idCounter.incrementAndGet());
            event.setEventId(id);
        }
        event.setUpdateTime(LocalDateTime.now());
        if (event.getCreateTime() == null) {
            event.setCreateTime(LocalDateTime.now());
        }
        store.put(event.getEventId(), event);
        return event;
    }

    @Override
    public Optional<Event> findById(String eventId) {
        return Optional.ofNullable(store.get(eventId));
    }

    @Override
    public List<Event> findAll() {
        return new ArrayList<>(store.values());
    }

    @Override
    public List<Event> findByStatus(EventStatus status) {
        return store.values().stream()
                .filter(e -> e.getStatus() == status)
                .collect(Collectors.toList());
    }

    @Override
    public Optional<Event> updateStatus(String eventId, EventStatus status) {
        return Optional.ofNullable(store.computeIfPresent(eventId, (id, event) -> {
            event.setStatus(status);
            event.setUpdateTime(LocalDateTime.now());
            return event;
        }));
    }

    @Override
    public void deleteById(String eventId) {
        store.remove(eventId);
    }

    @Override
    public long count() {
        return store.size();
    }
}
