package gc.mda.kcg.domain.aircraft;

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

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

@Service
@RequiredArgsConstructor
public class AircraftService {

    private final AircraftPositionRepository repository;

    /**
     * 시간 범위 내 항공기 위치를 조회하고 icao24 기준 최신 위치로 중복 제거하여 반환.
     */
    public List<AircraftDto> getByDateRange(String region, Instant from, Instant to) {
        List<AircraftPosition> positions = repository.findByRegionAndDateRange(region, from, to);

        Map<String, AircraftDto> deduplicated = new LinkedHashMap<>();
        for (AircraftPosition p : positions) {
            deduplicated.putIfAbsent(p.getIcao24(), toDto(p));
        }
        return List.copyOf(deduplicated.values());
    }

    private AircraftDto toDto(AircraftPosition p) {
        return AircraftDto.builder()
                .icao24(p.getIcao24())
                .callsign(p.getCallsign())
                .lat(p.getPosition() != null ? p.getPosition().getY() : 0.0)
                .lng(p.getPosition() != null ? p.getPosition().getX() : 0.0)
                .altitude(p.getAltitude() != null ? p.getAltitude() : 0.0)
                .velocity(p.getVelocity() != null ? p.getVelocity() : 0.0)
                .heading(p.getHeading() != null ? p.getHeading() : 0.0)
                .verticalRate(p.getVerticalRate() != null ? p.getVerticalRate() : 0.0)
                .onGround(p.getOnGround() != null && p.getOnGround())
                .category(p.getCategory())
                .typecode(p.getTypecode())
                .typeDesc(p.getTypeDesc())
                .registration(p.getRegistration())
                .operator(p.getOperator())
                .squawk(p.getSquawk())
                .lastSeen(p.getLastSeen() != null ? p.getLastSeen().toEpochMilli()
                        : p.getCollectedAt().toEpochMilli())
                .build();
    }
}
