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
    field :image_id, :binary_id

    belongs_to :product, SimpleshopTheme.Products.Product
    belongs_to :image, SimpleshopTheme.Media.Image, define_field: false

    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, :image_id])
    |> validate_required([:product_id, :src])
    |> foreign_key_constraint(:product_id)
    |> foreign_key_constraint(:image_id)
  end
end
