defmodule Towerops.Repo.Migrations.FixInterfaceStatsPrimaryKey do
  use Ecto.Migration

  def up do
    # Drop and recreate the table with correct primary key type
    # This is safe because interface stats are time-series data that regenerates
    drop table(:snmp_interface_stats)

    create table(:snmp_interface_stats, primary_key: false) do
      add :id, :binary_id, primary_key: true

      add :interface_id, references(:snmp_interfaces, type: :binary_id, on_delete: :delete_all),
        null: false

      add :if_in_octets, :bigint
      add :if_out_octets, :bigint
      add :if_in_errors, :bigint
      add :if_out_errors, :bigint
      add :if_in_discards, :bigint
      add :if_out_discards, :bigint
      add :checked_at, :utc_datetime, null: false

      timestamps(type: :utc_datetime, updated_at: false)
    end

    # Recreate indexes
    create index(:snmp_interface_stats, [:interface_id])
    create index(:snmp_interface_stats, [:interface_id, :checked_at])
    create index(:snmp_interface_stats, [:checked_at])
  end

  def down do
    # Recreate with old integer primary key
    drop table(:snmp_interface_stats)

    create table(:snmp_interface_stats) do
      add :interface_id, references(:snmp_interfaces, type: :binary_id, on_delete: :delete_all),
        null: false

      add :if_in_octets, :bigint
      add :if_out_octets, :bigint
      add :if_in_errors, :bigint
      add :if_out_errors, :bigint
      add :if_in_discards, :bigint
      add :if_out_discards, :bigint
      add :checked_at, :utc_datetime, null: false

      timestamps(type: :utc_datetime, updated_at: false)
    end

    create index(:snmp_interface_stats, [:interface_id])
    create index(:snmp_interface_stats, [:interface_id, :checked_at])
    create index(:snmp_interface_stats, [:checked_at])
  end
end
