defmodule Towerops.ConfigChanges.ConfigChangeEvent do
  @moduledoc """
  Schema for config change events linking MikroTik backup diffs to time windows.
  """
  use Ecto.Schema

  import Ecto.Changeset

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

  schema "config_change_events" do
    field :changed_at, :utc_datetime
    field :diff_summary, :string
    field :sections_changed, {:array, :string}, default: []
    field :change_size, :integer, default: 0

    belongs_to :device, Towerops.Devices.Device
    belongs_to :organization, Towerops.Organizations.Organization
    belongs_to :backup_before, Towerops.Devices.MikrotikBackup
    belongs_to :backup_after, Towerops.Devices.MikrotikBackup

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

  def changeset(event, attrs) do
    event
    |> cast(attrs, [
      :device_id,
      :organization_id,
      :backup_before_id,
      :backup_after_id,
      :changed_at,
      :diff_summary,
      :sections_changed,
      :change_size
    ])
    |> validate_required([:device_id, :organization_id, :changed_at])
    |> foreign_key_constraint(:device_id)
    |> foreign_key_constraint(:organization_id)
    |> foreign_key_constraint(:backup_before_id)
    |> foreign_key_constraint(:backup_after_id)
  end
end
