defmodule Berrypod.Orders.AbandonedCart do
  use Ecto.Schema
  import Ecto.Changeset

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

  schema "abandoned_carts" do
    field :customer_email, :string
    field :stripe_session_id, :string
    field :cart_total, :integer
    field :expired_at, :utc_datetime
    field :emailed_at, :utc_datetime

    belongs_to :order, Berrypod.Orders.Order

    timestamps(type: :utc_datetime)
  end

  def changeset(cart, attrs) do
    cart
    |> cast(attrs, [
      :customer_email,
      :order_id,
      :stripe_session_id,
      :cart_total,
      :expired_at,
      :emailed_at
    ])
    |> validate_required([:customer_email, :stripe_session_id, :expired_at])
    |> validate_format(:customer_email, ~r/@/)
    |> unique_constraint(:stripe_session_id)
  end
end
