defmodule Microwaveprop.Repo.Migrations.AddIsGridPointToHrrrProfiles do
  use Ecto.Migration

  def change do
    alter table(:hrrr_profiles) do
      add :is_grid_point, :boolean, default: false, null: false
    end

    create index(:hrrr_profiles, [:valid_time],
             where: "is_grid_point = true",
             name: :hrrr_profiles_grid_point_valid_time_idx
           )

    # Backfill is_grid_point in batches to avoid long-running single UPDATE
    flush()

    execute(
      """
      DO $$
      DECLARE
        batch_size INT := 50000;
        rows_updated INT := 1;
      BEGIN
        WHILE rows_updated > 0 LOOP
          UPDATE hrrr_profiles
          SET is_grid_point = true
          WHERE id IN (
            SELECT id FROM hrrr_profiles
            WHERE is_grid_point = false
              AND (lat * 1000)::int % 125 = 0
              AND (lon * 1000)::int % 125 = 0
            LIMIT batch_size
          );
          GET DIAGNOSTICS rows_updated = ROW_COUNT;
          RAISE NOTICE 'Updated % rows', rows_updated;
        END LOOP;
      END $$;
      """,
      "SELECT 1"
    )
  end
end
