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

  def change do
    rename table(:qsos), to: table(:contacts)

    rename table(:terrain_profiles), :qso_id, to: :contact_id

    # Rename indexes that reference the old table name
    execute "ALTER INDEX IF EXISTS qsos_pkey RENAME TO contacts_pkey",
            "ALTER INDEX IF EXISTS contacts_pkey RENAME TO qsos_pkey"

    execute "ALTER INDEX IF EXISTS qsos_band_index RENAME TO contacts_band_index",
            "ALTER INDEX IF EXISTS contacts_band_index RENAME TO qsos_band_index"

    execute "ALTER INDEX IF EXISTS qsos_distance_km_index RENAME TO contacts_distance_km_index",
            "ALTER INDEX IF EXISTS contacts_distance_km_index RENAME TO qsos_distance_km_index"

    execute "ALTER INDEX IF EXISTS qsos_qso_timestamp_index RENAME TO contacts_qso_timestamp_index",
            "ALTER INDEX IF EXISTS contacts_qso_timestamp_index RENAME TO qsos_qso_timestamp_index"

    execute "ALTER INDEX IF EXISTS qsos_station1_trgm_index RENAME TO contacts_station1_trgm_index",
            "ALTER INDEX IF EXISTS contacts_station1_trgm_index RENAME TO qsos_station1_trgm_index"

    execute "ALTER INDEX IF EXISTS qsos_station2_trgm_index RENAME TO contacts_station2_trgm_index",
            "ALTER INDEX IF EXISTS contacts_station2_trgm_index RENAME TO qsos_station2_trgm_index"

    execute "ALTER INDEX IF EXISTS qsos_hrrr_status_pending_index RENAME TO contacts_hrrr_status_pending_index",
            "ALTER INDEX IF EXISTS contacts_hrrr_status_pending_index RENAME TO qsos_hrrr_status_pending_index"

    execute "ALTER INDEX IF EXISTS qsos_weather_status_pending_index RENAME TO contacts_weather_status_pending_index",
            "ALTER INDEX IF EXISTS contacts_weather_status_pending_index RENAME TO qsos_weather_status_pending_index"

    execute "ALTER INDEX IF EXISTS qsos_terrain_status_pending_index RENAME TO contacts_terrain_status_pending_index",
            "ALTER INDEX IF EXISTS contacts_terrain_status_pending_index RENAME TO qsos_terrain_status_pending_index"

    execute "ALTER INDEX IF EXISTS qsos_iemre_status_pending_index RENAME TO contacts_iemre_status_pending_index",
            "ALTER INDEX IF EXISTS contacts_iemre_status_pending_index RENAME TO qsos_iemre_status_pending_index"

    # Rename terrain_profiles foreign key constraint
    execute "ALTER TABLE terrain_profiles RENAME CONSTRAINT terrain_profiles_qso_id_fkey TO terrain_profiles_contact_id_fkey",
            "ALTER TABLE terrain_profiles RENAME CONSTRAINT terrain_profiles_contact_id_fkey TO terrain_profiles_qso_id_fkey"

    execute "ALTER INDEX IF EXISTS terrain_profiles_qso_id_index RENAME TO terrain_profiles_contact_id_index",
            "ALTER INDEX IF EXISTS terrain_profiles_contact_id_index RENAME TO terrain_profiles_qso_id_index"
  end
end
