from __future__ import annotations

import os

import pytest

from app.modules.sync import repository as repo


@pytest.mark.skipif(
    "postgresql" not in os.environ.get("DATABASE_URL", ""),
    reason="RLS tests require PostgreSQL",
)
def test_rls_cross_enterprise():
    ent_a = repo.create_enterprise("Farm A", f"farm-a-{os.getpid()}")
    ent_b = repo.create_enterprise("Farm B", f"farm-b-{os.getpid()}")
    assert ent_a.id != ent_b.id
    hub_a = repo.create_farm_hub(ent_a.id, "Hub A", f"hub-a-{os.getpid()}", None)
    hubs_b = repo.list_farm_hubs(ent_b.id)
    assert all(h.id != hub_a.id for h in hubs_b)


def test_viewer_farm_scope(client):
    from uuid import uuid4

    from app.modules.users.repository import get_user_by_email

    slug = f"abac-{uuid4().hex[:8]}"
    ent = repo.create_enterprise("ABAC Farm", slug)
    admin = get_user_by_email("admin@compton.example")
    assert admin
    repo.add_member(admin.id, ent.id, "admin")
    hub1 = repo.create_farm_hub(ent.id, "H1", f"h1-{uuid4().hex[:8]}", None)
    hub2 = repo.create_farm_hub(ent.id, "H2", f"h2-{uuid4().hex[:8]}", None)
    viewer_id = admin.id
    repo.grant_farm_access(viewer_id, hub1.id)
    allowed = repo.list_farm_access(viewer_id, ent.id)
    assert hub1.id in allowed
    assert hub2.id not in allowed
