"""Repository tenant-scoped persistence tests."""
from __future__ import annotations

import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker

from app.core.database import engine
from app.models.foundation import Lead
from app.models.types import LeadPriority, LeadStatus
from app.repositories.foundation import LeadRepository
from app.tests.conftest import TENANT_A, TENANT_B


@pytest.mark.asyncio
async def test_lead_repository_tenant_isolation(db_setup):
    Session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    async with Session() as session:
        repo = LeadRepository(session)
        lead_a = Lead(
            tenant_id=TENANT_A,
            lead_number="LEAD-A1",
            first_name="A",
            last_name="One",
            full_name="A One",
            status=LeadStatus.NEW,
            priority=LeadPriority.MEDIUM,
            owner_user_id="owner-a",
        )
        lead_b = Lead(
            tenant_id=TENANT_B,
            lead_number="LEAD-B1",
            first_name="B",
            last_name="Two",
            full_name="B Two",
            status=LeadStatus.NEW,
            priority=LeadPriority.MEDIUM,
            owner_user_id="owner-b",
        )
        await repo.add(lead_a)
        await repo.add(lead_b)
        await session.commit()

        listed_a = await repo.list_by_tenant(TENANT_A, limit=50)
        listed_b = await repo.list_by_tenant(TENANT_B, limit=50)
        assert all(item.tenant_id == TENANT_A for item in listed_a)
        assert all(item.tenant_id == TENANT_B for item in listed_b)
        assert await repo.get(TENANT_B, lead_a.id) is None
        assert await repo.get(TENANT_A, lead_a.id) is not None
