defmodule Zoeyscomputer.Gists.Gist do
  alias Zoeyscomputer.IdGenerator
  use Ecto.Schema
  import Ecto.Changeset
  alias Zoeyscomputer.Users.User

  @primary_key {:id, :string, autogenerate: false}
  schema "gists" do
    field :code, :string
    field :lang, :string
    field :title, :string
    field :desc, :string
    belongs_to :author, User

    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(gist, attrs) do
    gist
    |> cast(attrs, [:code, :lang, :title, :desc, :author_id])
    |> validate_required([:code, :lang, :title, :author_id])
    |> put_new_id()
  end

  defp put_new_id(changeset) do
    IO.puts("assigning new id")

    case get_field(changeset, :id) do
      nil -> put_change(changeset, :id, IdGenerator.generate(7))
      _id -> changeset
    end
  end
end
