defmodule ZoeyscomputerWeb.GistControllerTest do
  use ZoeyscomputerWeb.ConnCase

  import Zoeyscomputer.GistsFixtures

  alias Zoeyscomputer.Gists.Gist

  @create_attrs %{
    code: "some code",
    lang: "some lang"
  }
  @update_attrs %{
    code: "some updated code",
    lang: "some updated lang"
  }
  @invalid_attrs %{code: nil, lang: nil}

  setup %{conn: conn} do
    {:ok, conn: put_req_header(conn, "accept", "application/json")}
  end

  describe "index" do
    test "lists all gists", %{conn: conn} do
      conn = get(conn, ~p"/api/gists")
      assert json_response(conn, 200)["data"] == []
    end
  end

  describe "create gist" do
    test "renders gist when data is valid", %{conn: conn} do
      conn = post(conn, ~p"/api/gists", gist: @create_attrs)
      assert %{"id" => id} = json_response(conn, 201)["data"]

      conn = get(conn, ~p"/api/gists/#{id}")

      assert %{
               "id" => ^id,
               "code" => "some code",
               "lang" => "some lang"
             } = json_response(conn, 200)["data"]
    end

    test "renders errors when data is invalid", %{conn: conn} do
      conn = post(conn, ~p"/api/gists", gist: @invalid_attrs)
      assert json_response(conn, 422)["errors"] != %{}
    end
  end

  describe "update gist" do
    setup [:create_gist]

    test "renders gist when data is valid", %{conn: conn, gist: %Gist{id: id} = gist} do
      conn = put(conn, ~p"/api/gists/#{gist}", gist: @update_attrs)
      assert %{"id" => ^id} = json_response(conn, 200)["data"]

      conn = get(conn, ~p"/api/gists/#{id}")

      assert %{
               "id" => ^id,
               "code" => "some updated code",
               "lang" => "some updated lang"
             } = json_response(conn, 200)["data"]
    end

    test "renders errors when data is invalid", %{conn: conn, gist: gist} do
      conn = put(conn, ~p"/api/gists/#{gist}", gist: @invalid_attrs)
      assert json_response(conn, 422)["errors"] != %{}
    end
  end

  describe "delete gist" do
    setup [:create_gist]

    test "deletes chosen gist", %{conn: conn, gist: gist} do
      conn = delete(conn, ~p"/api/gists/#{gist}")
      assert response(conn, 204)

      assert_error_sent 404, fn ->
        get(conn, ~p"/api/gists/#{gist}")
      end
    end
  end

  defp create_gist(_) do
    gist = gist_fixture()
    %{gist: gist}
  end
end
