defmodule Towerops.Organizations.Policy do
  @moduledoc """
  Authorization policy for organization resources.
  """

  alias Towerops.Organizations.Membership

  @doc """
  Checks if a user can perform an action on a resource within an organization.

  ## Examples

      iex> can?(%Membership{role: :owner}, :delete, :organization)
      true

      iex> can?(%Membership{role: :viewer}, :edit, :device)
      false
  """
  def can?(%Membership{role: role}, action, resource) do
    check_permission(role, action, resource)
  end

  def can?(nil, _action, _resource), do: false

  # Owner permissions - can do everything
  defp check_permission(:owner, _action, _resource), do: true

  # Admin permissions
  defp check_permission(:admin, :delete, :organization), do: false
  defp check_permission(:admin, _action, _resource), do: true

  # Member permissions
  defp check_permission(:member, action, :organization) when action in [:view, :list], do: true

  defp check_permission(:member, :delete, _resource), do: false
  defp check_permission(:member, action, :membership) when action in [:create, :edit], do: false
  defp check_permission(:member, action, :invitation) when action in [:create, :delete], do: false

  defp check_permission(:member, action, resource)
       when action in [:view, :list, :create, :edit] and resource in [:site, :device, :alert], do: true

  # Viewer permissions - read-only
  defp check_permission(:viewer, action, _resource) when action in [:view, :list], do: true
  defp check_permission(:viewer, :acknowledge, :alert), do: true
  defp check_permission(:viewer, _action, _resource), do: false
end
