defmodule ToweropsWeb.PlugExceptionsTest do
  use ToweropsWeb.ConnCase, async: true

  alias Plug.CSRFProtection.InvalidCSRFTokenError

  describe "Phoenix.NotAcceptableError protocol implementation" do
    test "implements status/1 callback" do
      exception = %Phoenix.NotAcceptableError{}
      status = Plug.Exception.status(exception)
      assert status == 400
    end

    test "implements actions/1 callback" do
      exception = %Phoenix.NotAcceptableError{}
      actions = Plug.Exception.actions(exception)
      assert actions == []
    end

    test "returns 400 status code when sent", %{conn: conn} do
      # Verify that when the exception is raised and handled by Phoenix,
      # it returns 400 (not 500) due to our protocol implementation
      assert_error_sent 400, fn ->
        conn
        |> put_req_header("accept", "application/invalid")
        |> get("/api/v1/sites")
      end
    end
  end

  describe "Plug.CSRFProtection.InvalidCSRFTokenError protocol implementation" do
    test "implements status/1 callback" do
      exception = %InvalidCSRFTokenError{}
      status = Plug.Exception.status(exception)
      assert status == 400
    end

    test "implements actions/1 callback" do
      exception = %InvalidCSRFTokenError{}
      actions = Plug.Exception.actions(exception)
      assert actions == []
    end

    test "returns 400 status code when exception is raised" do
      # Verify that the protocol converts the exception to 400
      # This simulates what Phoenix does when handling the exception
      exception = %InvalidCSRFTokenError{}

      # Phoenix checks Plug.Exception protocol to determine status code
      status = Plug.Exception.status(exception)
      assert status == 400

      # In production, this means Phoenix returns 400 instead of 500
      # when CSRF protection raises InvalidCSRFTokenError
    end
  end
end
