defmodule Towerops.Accounts.UserTotpDevice do
  @moduledoc """
  Schema for user TOTP (Time-based One-Time Password) devices.

  Allows users to register multiple authenticator apps (phone, tablet, etc.)
  for two-factor authentication.
  """
  use Ecto.Schema

  import Ecto.Changeset

  alias Towerops.Accounts.User

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "user_totp_devices" do
    field :name, :string
    field :totp_secret, :binary, redact: true
    field :last_used_at, :utc_datetime
    field :created_at, :utc_datetime

    belongs_to :user, User

    timestamps(type: :utc_datetime)
  end

  @doc """
  Changeset for creating or updating a TOTP device.
  """
  def changeset(device, attrs) do
    device
    |> cast(attrs, [:name, :totp_secret, :user_id, :created_at])
    |> validate_required([:name, :totp_secret, :user_id])
    |> validate_length(:name, min: 1, max: 100)
    |> foreign_key_constraint(:user_id)
  end

  @doc """
  Changeset for updating last_used_at timestamp.
  """
  def touch_changeset(device) do
    change(device, last_used_at: DateTime.utc_now(:second))
  end
end
