-- Test SGP4/SDP4 propagation functions
CREATE EXTENSION IF NOT EXISTS pg_orrery;

-- ISS TLE (LEO, near-earth -> SGP4)
WITH iss AS (
    SELECT '1 25544U 98067A   24001.50000000  .00016717  00000-0  10270-3 0  9025
2 25544  51.6400 208.9163 0006703  30.1694  61.7520 15.50100486 00001'::tle AS t
)
SELECT
    round(eci_x(sgp4_propagate(t, '2024-01-01 12:00:00+00'))::numeric, 1) AS x_km,
    round(eci_y(sgp4_propagate(t, '2024-01-01 12:00:00+00'))::numeric, 1) AS y_km,
    round(eci_z(sgp4_propagate(t, '2024-01-01 12:00:00+00'))::numeric, 1) AS z_km,
    round(eci_speed(sgp4_propagate(t, '2024-01-01 12:00:00+00'))::numeric, 3) AS speed_kms,
    round(eci_altitude(sgp4_propagate(t, '2024-01-01 12:00:00+00'))::numeric, 0) AS alt_km
FROM iss;

-- Propagation 1 hour after epoch
WITH iss AS (
    SELECT '1 25544U 98067A   24001.50000000  .00016717  00000-0  10270-3 0  9025
2 25544  51.6400 208.9163 0006703  30.1694  61.7520 15.50100486 00001'::tle AS t
)
SELECT
    round(eci_speed(sgp4_propagate(t, '2024-01-01 13:00:00+00'))::numeric, 3) AS speed_1h,
    round(eci_altitude(sgp4_propagate(t, '2024-01-01 13:00:00+00'))::numeric, 0) AS alt_1h
FROM iss;

-- GPS satellite (MEO, deep-space -> SDP4)
WITH gps AS (
    SELECT '1 28874U 05038A   24001.50000000  .00000012  00000+0  00000+0 0  9993
2 28874  55.4408 300.3467 0117034  51.6543 309.5420  2.00557079 00006'::tle AS t
)
SELECT
    round(eci_speed(sgp4_propagate(t, '2024-01-01 12:00:00+00'))::numeric, 3) AS gps_speed,
    round(eci_altitude(sgp4_propagate(t, '2024-01-01 12:00:00+00'))::numeric, 0) AS gps_alt
FROM gps;

-- Propagation series: ISS, 10 minute steps over 1 orbit (~93 min)
WITH iss AS (
    SELECT '1 25544U 98067A   24001.50000000  .00016717  00000-0  10270-3 0  9025
2 25544  51.6400 208.9163 0006703  30.1694  61.7520 15.50100486 00001'::tle AS t
)
SELECT
    count(*) AS num_points,
    round(min(sqrt(x*x + y*y + z*z) - 6378.135)::numeric, 0) AS min_alt,
    round(max(sqrt(x*x + y*y + z*z) - 6378.135)::numeric, 0) AS max_alt
FROM iss, sgp4_propagate_series(t, '2024-01-01 12:00:00+00', '2024-01-01 13:33:00+00', '10 minutes');

-- Distance between ISS and GPS at epoch
WITH sats AS (
    SELECT '1 25544U 98067A   24001.50000000  .00016717  00000-0  10270-3 0  9025
2 25544  51.6400 208.9163 0006703  30.1694  61.7520 15.50100486 00001'::tle AS iss,
    '1 28874U 05038A   24001.50000000  .00000012  00000+0  00000+0 0  9993
2 28874  55.4408 300.3467 0117034  51.6543 309.5420  2.00557079 00006'::tle AS gps
)
SELECT
    round(tle_distance(iss, gps, '2024-01-01 12:00:00+00')::numeric, 0) AS dist_km,
    round(tle_distance(iss, iss, '2024-01-01 12:00:00+00')::numeric, 6) AS self_dist
FROM sats;

-- Distance to self should be zero
WITH iss AS (
    SELECT '1 25544U 98067A   24001.50000000  .00016717  00000-0  10270-3 0  9025
2 25544  51.6400 208.9163 0006703  30.1694  61.7520 15.50100486 00001'::tle AS t
)
SELECT
    tle_distance(t, t, '2024-01-01 12:00:00+00') = 0.0 AS self_is_zero
FROM iss;
