defmodule Towerops.Devices.BackupRequest do
  @moduledoc """
  Schema for MikroTik device backup request tracking.
  """
  use Ecto.Schema

  import Ecto.Changeset

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

  schema "device_backup_requests" do
    field :job_id, :string
    field :requested_at, :utc_datetime
    field :completed_at, :utc_datetime
    field :status, :string
    field :error_message, :string
    field :source, :string

    belongs_to :device, Towerops.Devices.Device

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

  @doc false
  def changeset(backup_request, attrs) do
    backup_request
    |> cast(attrs, [
      :device_id,
      :job_id,
      :requested_at,
      :completed_at,
      :status,
      :error_message,
      :source
    ])
    |> validate_required([:device_id, :job_id, :requested_at, :status, :source])
    |> validate_inclusion(:status, ["pending", "success", "failed", "timeout"])
    |> validate_inclusion(:source, ["manual", "daily_cron"])
    |> foreign_key_constraint(:device_id)
  end
end
