defmodule BerrypodWeb.UnsubscribeControllerTest do
  use BerrypodWeb.ConnCase, async: true

  alias Berrypod.Orders

  defp sign_token(email) do
    Phoenix.Token.sign(BerrypodWeb.Endpoint, "email-unsub", email)
  end

  describe "GET /unsubscribe/:token" do
    test "valid token: suppresses email and returns 200", %{conn: conn} do
      token = sign_token("unsub@example.com")
      conn = get(conn, ~p"/unsubscribe/#{token}")

      assert conn.status == 200
      assert conn.resp_body =~ "Unsubscribed"
      assert Orders.check_suppression("unsub@example.com") == :suppressed
    end

    test "invalid token returns 400", %{conn: conn} do
      conn = get(conn, ~p"/unsubscribe/bad_token_here")

      assert conn.status == 400
      assert conn.resp_body =~ "invalid or expired"
    end

    test "already suppressed — idempotent, still returns 200", %{conn: conn} do
      Orders.add_suppression("already@example.com", "unsubscribed")
      token = sign_token("already@example.com")
      conn = get(conn, ~p"/unsubscribe/#{token}")

      assert conn.status == 200
      assert Orders.check_suppression("already@example.com") == :suppressed
    end
  end
end
