985 B · text History 4b6fe3b
defmodule OhMyExOhIrcd.Channels.ChannelMembership do
  @moduledoc """
  Persisted per-user channel access (admin/op/halfop/voice). Founder is
  stored separately on `channels.founder_user_id` and is implicit; only
  granted access at or below admin lives here.
  """

  use Ecto.Schema
  import Ecto.Changeset

  alias OhMyExOhIrcd.Accounts.User
  alias OhMyExOhIrcd.Channels.ChannelRecord

  @valid_access ~w(founder admin op halfop voice)

  schema "channel_memberships" do
    field :access, :string

    belongs_to :channel, ChannelRecord
    belongs_to :user, User

    timestamps(type: :utc_datetime)
  end

  def changeset(record, attrs) do
    record
    |> cast(attrs, [:channel_id, :user_id, :access])
    |> validate_required([:channel_id, :user_id, :access])
    |> validate_inclusion(:access, @valid_access)
    |> assoc_constraint(:channel)
    |> assoc_constraint(:user)
    |> unique_constraint([:channel_id, :user_id])
  end

  def valid_access, do: @valid_access
end