defmodule Zoeyscomputer.ApiKeys.ApiKey do
  use Ecto.Schema
  import Ecto.Changeset
  alias Zoeyscomputer.Users.User

  schema "api_keys" do
    field :name, :string
    field :token, :string
    belongs_to :user, User

    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(api_key, attrs) do
    api_key
    # Make sure both fields are in cast
    |> cast(attrs, [:name, :user_id])
    |> validate_required([:name, :user_id])
    # This needs to happen before validation
    |> put_token()
    # Add token to required fields
    |> validate_required([:token])
  end

  defp put_token(changeset) do
    case changeset do
      %Ecto.Changeset{valid?: true} ->
        token = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
        put_change(changeset, :token, token)

      _ ->
        changeset
    end
  end
end
