CREATE EXTENSION IF NOT EXISTS postgis;

ALTER TABLE features
  ADD COLUMN IF NOT EXISTS geom geometry(PointZ, 4326);

UPDATE features
SET geom = ST_SetSRID(
  ST_MakePoint(
    (geometry->'coordinates'->>0)::double precision,
    (geometry->'coordinates'->>1)::double precision,
    CASE
      WHEN jsonb_array_length(geometry->'coordinates') >= 3 THEN (geometry->'coordinates'->>2)::double precision
      ELSE 0
    END
  ),
  4326
)
WHERE geom IS NULL
  AND geometry ? 'coordinates';

CREATE INDEX IF NOT EXISTS idx_features_geom_gist ON features USING GIST (geom);
