package com.ai.trackwalker.uavaccess.wayline;

import com.ai.trackwalker.uavaccess.config.UavAccessProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class WaylineReconciliationJob {
    private static final Logger LOGGER = LoggerFactory.getLogger(WaylineReconciliationJob.class);

    private final UavAccessProperties properties;
    private final JdbcTemplate jdbc;
    private final WaylineService waylines;

    public WaylineReconciliationJob(
            UavAccessProperties properties,
            JdbcTemplate jdbc,
            WaylineService waylines
    ) {
        this.properties = properties;
        this.jdbc = jdbc;
        this.waylines = waylines;
    }

    @Scheduled(fixedDelayString = "${uav-access.flighthub.wayline-reconciliation-delay-ms:10000}")
    public void reconcile() {
        if (!properties.getFlighthub().isEnabled()) return;
        List<String> ids = jdbc.queryForList("""
                select id from route_vendor_artifacts
                where import_state='IMPORTING'
                order by updated_at
                limit 50
                """, String.class);
        for (String id : ids) {
            try {
                waylines.refresh(id);
            } catch (RuntimeException exception) {
                LOGGER.warn("Unable to reconcile FlightHub wayline {}", id, exception);
            }
        }
    }
}
