defmodule ToweropsWeb.Api.MobileControllerTest do
  use ToweropsWeb.ConnCase, async: true

  import Towerops.AccountsFixtures

  alias Towerops.MobileSessions
  alias Towerops.Organizations

  setup do
    user = user_fixture()
    {:ok, organization} = Organizations.create_organization(%{name: "Test Org"}, user.id)

    {:ok, session} =
      MobileSessions.create_mobile_session(%{
        user_id: user.id,
        device_name: "Test iPhone"
      })

    conn = put_req_header(build_conn(), "authorization", "Bearer #{session.token}")

    %{conn: conn, user: user, organization: organization, session: session}
  end

  describe "list_organizations" do
    test "returns user organizations", %{conn: conn} do
      conn = get(conn, ~p"/api/v1/mobile/organizations")

      assert %{"organizations" => orgs} = json_response(conn, 200)
      assert orgs != []
      assert hd(orgs)["name"] == "Test Org"
    end
  end

  describe "list_sites" do
    test "returns sites for organization", %{conn: conn, organization: org} do
      {:ok, _site} =
        Towerops.Sites.create_site(%{
          name: "Test Site",
          organization_id: org.id
        })

      conn = get(conn, ~p"/api/v1/mobile/organizations/#{org.id}/sites")

      assert %{"sites" => sites} = json_response(conn, 200)
      assert length(sites) == 1
      assert hd(sites)["name"] == "Test Site"
    end

    test "returns forbidden for non-member organization", %{conn: conn} do
      other_user = user_fixture()
      {:ok, other_org} = Organizations.create_organization(%{name: "Other Org"}, other_user.id)

      conn = get(conn, ~p"/api/v1/mobile/organizations/#{other_org.id}/sites")

      assert json_response(conn, 403)["error"] =~ "Access denied"
    end
  end

  describe "list_alerts" do
    test "returns alerts for organization", %{conn: conn, organization: org} do
      conn = get(conn, ~p"/api/v1/mobile/organizations/#{org.id}/alerts")

      assert %{"alerts" => _alerts} = json_response(conn, 200)
    end
  end
end
