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

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

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

      add :sensor_id, references(:snmp_sensors, type: :binary_id, on_delete: :delete_all),
        null: false

      add :value, :float
      add :status, :string, null: false
      add :checked_at, :utc_datetime, null: false

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

    # Recreate indexes
    create index(:snmp_sensor_readings, [:sensor_id])
    create index(:snmp_sensor_readings, [:sensor_id, :checked_at])
    create index(:snmp_sensor_readings, [:status])
    create index(:snmp_sensor_readings, [:checked_at])
  end

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

    create table(:snmp_sensor_readings) do
      add :sensor_id, references(:snmp_sensors, type: :binary_id, on_delete: :delete_all),
        null: false

      add :value, :float
      add :status, :string, null: false
      add :checked_at, :utc_datetime, null: false

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

    create index(:snmp_sensor_readings, [:sensor_id])
    create index(:snmp_sensor_readings, [:sensor_id, :checked_at])
    create index(:snmp_sensor_readings, [:status])
    create index(:snmp_sensor_readings, [:checked_at])
  end
end
