"""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 LoyaltyProgram
from app.models.types import ProgramStatus
from app.repositories.foundation import LoyaltyProgramRepository
from app.tests.conftest import TENANT_A, TENANT_B


@pytest.mark.asyncio
async def test_program_repository_tenant_isolation(db_setup):
    Session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    async with Session() as session:
        repo = LoyaltyProgramRepository(session)
        program_a = LoyaltyProgram(
            tenant_id=TENANT_A,
            code="A1",
            name="Program A",
            status=ProgramStatus.ACTIVE,
        )
        program_b = LoyaltyProgram(
            tenant_id=TENANT_B,
            code="B1",
            name="Program B",
            status=ProgramStatus.ACTIVE,
        )
        await repo.add(program_a)
        await repo.add(program_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, program_a.id) is None
        assert await repo.get(TENANT_A, program_a.id) is not None
