defmodule SimpleshopTheme.Products.ProductImage do
  @moduledoc """
  Schema for product images.

  Images are ordered by position and belong to a single product.
  """

  use Ecto.Schema
  import Ecto.Changeset

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

  schema "product_images" do
    field :src, :string
    field :position, :integer, default: 0
    field :alt, :string

    belongs_to :product, SimpleshopTheme.Products.Product

    timestamps(type: :utc_datetime)
  end

  @doc """
  Changeset for creating or updating a product image.
  """
  def changeset(product_image, attrs) do
    product_image
    |> cast(attrs, [:product_id, :src, :position, :alt])
    |> validate_required([:product_id, :src])
    |> foreign_key_constraint(:product_id)
  end
end
