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

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

  schema "social_identities" do
    field :provider, Ecto.Enum,
      values: [:github, :google, :instagram, :facebook, :telegram, :other]

    field :provider_uid, :string
    field :profile_url, :string
    field :handle, :string
    field :verified_at, :utc_datetime
    belongs_to :user, WhoNeedHelp.Accounts.User
    timestamps(type: :utc_datetime)
  end

  def changeset(identity, attrs) do
    identity
    |> cast(attrs, [:provider, :profile_url, :handle])
    |> validate_required([:provider, :profile_url, :user_id])
    |> validate_format(:profile_url, ~r/^https:\/\/[^\s]+$/i,
      message: "must be a complete HTTPS URL"
    )
    |> validate_length(:profile_url, max: 255)
    |> validate_length(:handle, max: 100)
    |> unique_constraint([:provider, :provider_uid])
  end

  def verified_changeset(identity, attrs) do
    identity
    |> cast(attrs, [
      :provider,
      :provider_uid,
      :profile_url,
      :handle,
      :verified_at,
      :user_id
    ])
    |> validate_required([
      :provider,
      :provider_uid,
      :profile_url,
      :verified_at,
      :user_id
    ])
    |> validate_inclusion(:provider, [:github])
    |> validate_format(:profile_url, ~r/^https:\/\/github\.com\/[^\s\/]+\/?$/i,
      message: "must be a GitHub profile URL"
    )
    |> validate_length(:provider_uid, max: 255)
    |> validate_length(:profile_url, max: 255)
    |> validate_length(:handle, max: 100)
    |> unique_constraint([:provider, :provider_uid])
  end
end
