defmodule ToweropsWeb.Plugs.CheckPolicyConsent do
  @moduledoc """
  Plug to check if authenticated users need to re-consent to updated policies.

  This plug checks if there are any policy versions newer than the user's
  last consent and stores the list of policies requiring re-consent in assigns.

  The component can then display a modal prompting the user to accept the
  updated policies before continuing.
  """
  import Plug.Conn

  alias Towerops.Accounts

  def init(opts), do: opts

  def call(conn, _opts) do
    case conn.assigns[:current_user] do
      nil ->
        # Not authenticated, no need to check consent
        assign(conn, :policies_needing_consent, [])

      user ->
        # Check if user needs to re-consent to any policies
        policies_needing_consent = Accounts.policies_needing_reconsent(user.id)
        assign(conn, :policies_needing_consent, policies_needing_consent)
    end
  end
end
