defmodule DaProductApp.YspConfiguration do use Ecto.Schema import Ecto.Changeset @primary_key {:id, :id, autogenerate: true} schema "ysp_configurations" do field :merchant_id, :string field :notification_url, :string field :merchant_tag, :string field :bank_user_id, :string field :terminal_id, :string field :shop_id, :string field :cash_desk_id, :string field :max_retry_attempts, :integer, default: 3 field :retry_interval_seconds, :integer, default: 30 field :is_active, :boolean, default: true timestamps() end @doc false def changeset(ysp_configuration, attrs) do ysp_configuration |> cast(attrs, [ :merchant_id, :notification_url, :merchant_tag, :bank_user_id, :terminal_id, :shop_id, :cash_desk_id, :max_retry_attempts, :retry_interval_seconds, :is_active ]) |> validate_required([:merchant_id, :notification_url]) |> validate_url(:notification_url) |> validate_number(:max_retry_attempts, greater_than: 0, less_than_or_equal_to: 10) |> validate_number(:retry_interval_seconds, greater_than: 0) |> unique_constraint(:merchant_id) end defp validate_url(changeset, field) do validate_change(changeset, field, fn _, value -> case URI.parse(value) do %URI{scheme: scheme} when scheme in ["http", "https"] -> [] _ -> [{field, "must be a valid HTTP/HTTPS URL"}] end end) end @doc """ Gets configuration for a merchant, falling back to default if not found. """ def get_config_for_merchant(merchant_id) do case DaProductApp.Repo.get_by(__MODULE__, merchant_id: merchant_id, is_active: true) do nil -> # Fall back to default configuration DaProductApp.Repo.get_by(__MODULE__, merchant_id: "default", is_active: true) config -> config end end end