defmodule Tarakan.Repo.Migrations.RenameEpidemicTables do
  use Ecto.Migration

  # Postgres keeps old index/constraint names across ALTER TABLE ... RENAME,
  # so they are renamed explicitly below.
  @indexes [
    {"epidemic_patterns_rank_7d_idx", "infestation_patterns_rank_7d_idx"},
    {"epidemic_patterns_rank_30d_idx", "infestation_patterns_rank_30d_idx"},
    {"epidemic_patterns_rank_90d_idx", "infestation_patterns_rank_90d_idx"},
    {"epidemic_patterns_rank_365d_idx", "infestation_patterns_rank_365d_idx"},
    {"epidemic_pattern_repos_pattern_recent_idx", "infestation_pattern_repos_pattern_recent_idx"},
    {"epidemic_pattern_repos_repository_id_index",
     "infestation_pattern_repos_repository_id_index"},
    # These two default names already hit the 63-char identifier limit; the new
    # names stay within it instead of re-truncating.
    {"epidemic_pattern_instances_pattern_key_canonical_finding_id_index",
     "infestation_pattern_instances_pattern_canonical_idx"},
    {"epidemic_pattern_instances_pattern_key_updated_at_index",
     "infestation_pattern_instances_pattern_key_updated_at_index"},
    {"epidemic_pattern_instances_status_updated_at_pattern_key_index",
     "infestation_pattern_instances_status_window_idx"},
    {"epidemic_pattern_instances_repository_id_index",
     "infestation_pattern_instances_repository_id_index"}
  ]

  @constraints [
    {"infestation_patterns", "epidemic_patterns_pkey", "infestation_patterns_pkey"},
    {"infestation_pattern_repos", "epidemic_pattern_repos_pkey",
     "infestation_pattern_repos_pkey"},
    {"infestation_pattern_instances", "epidemic_pattern_instances_pkey",
     "infestation_pattern_instances_pkey"},
    {"infestation_pattern_repos", "epidemic_pattern_repos_repository_id_fkey",
     "infestation_pattern_repos_repository_id_fkey"},
    {"infestation_pattern_instances", "epidemic_pattern_instances_canonical_finding_id_fkey",
     "infestation_pattern_instances_canonical_finding_id_fkey"},
    {"infestation_pattern_instances", "epidemic_pattern_instances_repository_id_fkey",
     "infestation_pattern_instances_repository_id_fkey"}
  ]

  def change do
    rename table(:epidemic_patterns), to: table(:infestation_patterns)
    rename table(:epidemic_pattern_instances), to: table(:infestation_pattern_instances)
    rename table(:epidemic_pattern_repos), to: table(:infestation_pattern_repos)

    for {old, new} <- @indexes do
      execute "ALTER INDEX #{old} RENAME TO #{new}",
              "ALTER INDEX #{new} RENAME TO #{old}"
    end

    for {table, old, new} <- @constraints do
      execute "ALTER TABLE #{table} RENAME CONSTRAINT #{old} TO #{new}",
              "ALTER TABLE #{table} RENAME CONSTRAINT #{new} TO #{old}"
    end
  end
end
