defmodule Towerops.Accounts.User do
  @moduledoc """
  User schema for authentication and authorization.

  Users can own or be members of multiple organizations and authenticate via:
  - Email/password
  - TOTP (Time-based One-Time Password) two-factor authentication
  - Session tokens
  """
  use Ecto.Schema

  import Ecto.Changeset

  alias Ecto.Association.NotLoaded
  alias Towerops.Organizations.Membership
  alias Towerops.Organizations.Organization

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "users" do
    field :email, :string
    field :password, :string, virtual: true, redact: true
    field :hashed_password, :string, redact: true
    field :confirmed_at, :utc_datetime
    field :authenticated_at, :utc_datetime, virtual: true
    field :is_superuser, :boolean, default: false
    field :first_name, :string
    field :last_name, :string
    field :timezone, :string, default: "UTC"
    field :time_format, :string, default: "24h"
    field :totp_secret, :binary, redact: true
    field :totp_verified_at, :utc_datetime, virtual: true
    field :privacy_policy_consent, :boolean, virtual: true
    field :terms_of_service_consent, :boolean, virtual: true
    field :password_breach_count, :integer, virtual: true
    field :device_count, :integer, virtual: true
    field :last_sudo_at, :utc_datetime

    has_many :memberships, Membership
    has_many :organizations, through: [:memberships, :organization]
    belongs_to :default_organization, Organization

    timestamps(type: :utc_datetime)
  end

  @type t :: %__MODULE__{
          id: Ecto.UUID.t(),
          email: String.t(),
          password: String.t() | nil,
          hashed_password: String.t(),
          confirmed_at: DateTime.t() | nil,
          authenticated_at: DateTime.t() | nil,
          is_superuser: boolean(),
          first_name: String.t() | nil,
          last_name: String.t() | nil,
          timezone: String.t(),
          totp_secret: binary() | nil,
          totp_verified_at: DateTime.t() | nil,
          last_sudo_at: DateTime.t() | nil,
          memberships: NotLoaded.t() | [Membership.t()],
          organizations: NotLoaded.t() | [Organization.t()],
          inserted_at: DateTime.t(),
          updated_at: DateTime.t()
        }

  @doc """
  A user changeset for registering or changing the email.

  It requires the email to change otherwise an error is added.

  ## Options

    * `:validate_unique` - Set to false if you don't want to validate the
      uniqueness of the email, useful when displaying live validations.
      Defaults to `true`.
  """
  def email_changeset(user, attrs, opts \\ []) do
    user
    |> cast(attrs, [:email])
    |> validate_email(opts)
  end

  defp validate_email(changeset, opts) do
    changeset =
      changeset
      |> validate_required([:email])
      |> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/, message: "must have the @ sign and no spaces")
      |> validate_length(:email, max: 160)

    if Keyword.get(opts, :validate_unique, true) do
      changeset
      |> unsafe_validate_unique(:email, Towerops.Repo)
      |> unique_constraint(:email)
      |> validate_email_changed()
    else
      changeset
    end
  end

  defp validate_email_changed(changeset) do
    if get_field(changeset, :email) && get_change(changeset, :email) == nil do
      add_error(changeset, :email, "did not change")
    else
      changeset
    end
  end

  @doc """
  A user changeset for updating the profile information (first_name, last_name, timezone).
  """
  def profile_changeset(user, attrs) do
    user
    |> cast(attrs, [:first_name, :last_name, :timezone, :time_format, :default_organization_id])
    |> validate_length(:first_name, max: 100)
    |> validate_length(:last_name, max: 100)
    |> validate_length(:timezone, max: 100)
    |> validate_inclusion(:time_format, ["12h", "24h"])
    |> foreign_key_constraint(:default_organization_id)
  end

  @doc """
  A user changeset for registration with email and password.

  ## Options

    * `:hash_password` - Hashes the password so it can be stored securely
      in the database and ensures the password field is cleared to prevent
      leaks in the logs. Defaults to `true`.

    * `:validate_unique` - Set to false if you don't want to validate the
      uniqueness of the email, useful when displaying live validations.
      Defaults to `true`.
  """
  def registration_changeset(user, attrs, opts \\ []) do
    user
    |> cast(attrs, [
      :email,
      :password,
      :first_name,
      :last_name,
      :timezone,
      :privacy_policy_consent,
      :terms_of_service_consent
    ])
    |> validate_email_for_registration(opts)
    |> validate_password(opts)
    |> validate_consent()
    |> validate_timezone()
    |> validate_length(:first_name, max: 100)
    |> validate_length(:last_name, max: 100)
  end

  defp validate_consent(changeset) do
    changeset
    |> validate_acceptance(:privacy_policy_consent,
      message: "must be accepted to create an account"
    )
    |> validate_acceptance(:terms_of_service_consent,
      message: "must be accepted to create an account"
    )
  end

  defp validate_timezone(changeset) do
    validate_change(changeset, :timezone, fn :timezone, timezone ->
      validate_timezone_value(timezone)
    end)
  end

  defp validate_timezone_value(timezone) when is_nil(timezone) or timezone == "", do: []

  defp validate_timezone_value(timezone) do
    # Validate by attempting to shift a datetime to the given timezone
    # This works with Calendar.UTCOnlyTimeZoneDatabase which only accepts "Etc/UTC" and "UTC"
    # For full IANA timezone support, tzdata package would be needed
    case DateTime.shift_zone(DateTime.utc_now(), timezone) do
      {:ok, _} -> []
      {:error, _} -> [timezone: "is not a valid timezone"]
    end
  end

  defp validate_email_for_registration(changeset, opts) do
    changeset =
      changeset
      |> validate_required([:email])
      |> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/, message: "must have the @ sign and no spaces")
      |> validate_length(:email, max: 160)

    if Keyword.get(opts, :validate_unique, true) do
      changeset
      |> unsafe_validate_unique(:email, Towerops.Repo)
      |> unique_constraint(:email)
    else
      changeset
    end
  end

  @doc """
  A user changeset for changing the password.

  It is important to validate the length of the password, as long passwords may
  be very expensive to hash for certain algorithms.

  ## Options

    * `:hash_password` - Hashes the password so it can be stored securely
      in the database and ensures the password field is cleared to prevent
      leaks in the logs. If password hashing is not needed and clearing the
      password field is not desired (like when using this changeset for
      validations on a LiveView form), this option can be set to `false`.
      Defaults to `true`.
  """
  def password_changeset(user, attrs, opts \\ []) do
    user
    |> cast(attrs, [:password])
    |> validate_confirmation(:password, message: "does not match password")
    |> validate_password(opts)
  end

  defp validate_password(changeset, opts) do
    changeset
    |> validate_required([:password])
    |> validate_length(:password, min: 12, max: 72)
    # Examples of additional password validation:
    # |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character")
    # |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character")
    # |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character")
    |> maybe_hash_password(opts)
  end

  defp maybe_hash_password(changeset, opts) do
    hash_password? = Keyword.get(opts, :hash_password, true)
    password = get_change(changeset, :password)

    if hash_password? && password && changeset.valid? do
      changeset
      # Hashing could be done with `Ecto.Changeset.prepare_changes/2`, but that
      # would keep the database transaction open longer and hurt performance.
      |> put_change(:hashed_password, Argon2.hash_pwd_salt(password))
      |> delete_change(:password)
    else
      changeset
    end
  end

  @doc """
  Confirms the account by setting `confirmed_at`.
  """
  def confirm_changeset(user) do
    now = DateTime.utc_now(:second)
    change(user, confirmed_at: now)
  end

  @doc """
  Changeset for updating sudo mode timestamp.
  """
  def sudo_changeset(user, attrs) do
    user
    |> cast(attrs, [:last_sudo_at])
    |> validate_required([:last_sudo_at])
  end

  @doc """
  Verifies the password.

  If there is no user or the user doesn't have a password, we call
  `Argon2.no_user_verify/0` to avoid timing attacks.
  """
  def valid_password?(%Towerops.Accounts.User{hashed_password: hashed_password}, password)
      when is_binary(hashed_password) and byte_size(password) > 0 do
    Argon2.verify_pass(password, hashed_password)
  end

  def valid_password?(_, _) do
    Argon2.no_user_verify()
    false
  end

  @doc """
  Returns the user's full name by combining first_name and last_name.

  Returns nil if both fields are nil or empty.
  """
  @spec full_name(t()) :: String.t() | nil
  def full_name(%__MODULE__{first_name: first, last_name: last}) do
    [first, last]
    |> Enum.reject(&(is_nil(&1) or &1 == ""))
    |> case do
      [] -> nil
      parts -> Enum.join(parts, " ")
    end
  end
end
