defmodule WhoNeedHelp.Accounts.AuthIdentity do
  use Ecto.Schema
  import Ecto.Changeset

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

  schema "auth_identities" do
    field :provider, Ecto.Enum, values: [:google]
    field :provider_uid, :string
    field :email, :string
    belongs_to :user, WhoNeedHelp.Accounts.User

    timestamps(type: :utc_datetime)
  end

  def changeset(identity, attrs) do
    identity
    |> cast(attrs, [:provider, :provider_uid, :email, :user_id])
    |> update_change(:email, &normalize_email/1)
    |> validate_required([:provider, :provider_uid, :email, :user_id])
    |> validate_inclusion(:provider, [:google])
    |> validate_length(:provider_uid, min: 1, max: 255)
    |> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/,
      message: "must have the @ sign and no spaces"
    )
    |> validate_length(:email, max: 160)
    |> unique_constraint([:provider, :provider_uid])
    |> unique_constraint([:user_id, :provider])
  end

  defp normalize_email(email) when is_binary(email),
    do: email |> String.trim() |> String.downcase()

  defp normalize_email(email), do: email
end
