defmodule Towerops.Devices.MikrotikBackup do
  @moduledoc """
  Schema for MikroTik device configuration backups.
  """
  use Ecto.Schema

  import Ecto.Changeset

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

  schema "device_mikrotik_backups" do
    field :config_compressed, :binary
    field :config_hash, :string
    field :config_hash_normalized, :string
    field :config_size_bytes, :integer
    field :compressed_size_bytes, :integer
    field :backed_up_at, :utc_datetime
    field :trigger_source, :string

    belongs_to :device, Towerops.Devices.Device

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

  @doc false
  def changeset(backup, attrs) do
    backup
    |> cast(attrs, [
      :device_id,
      :config_compressed,
      :config_hash,
      :config_hash_normalized,
      :config_size_bytes,
      :compressed_size_bytes,
      :backed_up_at,
      :trigger_source
    ])
    |> validate_required([
      :device_id,
      :config_compressed,
      :config_hash,
      :config_hash_normalized,
      :backed_up_at
    ])
    |> foreign_key_constraint(:device_id)
  end
end
