defmodule Prymn.Apps.App do
  use Ecto.Schema

  import Ecto.Changeset

  schema "apps" do
    belongs_to :server, Prymn.Servers.Server
    field :name, :string
    field :type, :string
    field :status, Ecto.Enum, values: [:initialized, :deployed], default: :initialized
    embeds_one :wordpress, Prymn.Apps.Wordpress, source: :metadata, on_replace: :update
    # embeds_one :html, Prymn.Apps.Html, source: :metadata, on_replace: :update

    timestamps()
  end

  @doc false
  def changeset(app, attrs) do
    app
    |> cast(attrs, [:name])
    |> validate_required([:name, :server_id])
  end

  @doc false
  def change_wordpress(app, attrs \\ %{}) do
    app
    |> changeset(attrs)
    |> cast_embed(:wordpress)
    |> validate_required(:wordpress)
    |> put_change(:type, "wordpress")
    |> put_change(:status, :initialized)
  end
end