defmodule Towerops.Devices.DeviceFirmwareHistory do
  @moduledoc """
  Schema for tracking firmware version changes on individual devices over time.

  This is an append-only audit log that records when a device's firmware version
  changes (detected during SNMP discovery or polling). Each record represents a
  single version change event.

  The `firmware_releases` table stores the latest available versions from vendors.
  """

  use Ecto.Schema

  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  schema "device_firmware_history" do
    belongs_to :snmp_device, Towerops.Snmp.Device

    field :old_version, :string
    field :new_version, :string
    field :detected_at, :utc_datetime
    field :detection_method, :string

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

  @doc """
  Changeset for recording a firmware version change on a device.

  Required fields:
  - `snmp_device_id` - The device that changed firmware
  - `new_version` - The new firmware version detected
  - `detected_at` - When the change was detected

  Optional fields:
  - `old_version` - Previous version (nil for first discovery)
  - `detection_method` - How the change was detected ("discovery", "polling", "manual")
  """
  def changeset(device_firmware_history, attrs) do
    device_firmware_history
    |> cast(attrs, [
      :snmp_device_id,
      :old_version,
      :new_version,
      :detected_at,
      :detection_method
    ])
    |> validate_required([:snmp_device_id, :new_version, :detected_at])
    |> foreign_key_constraint(:snmp_device_id)
  end
end
