"""Requires an explicitly isolated fixture DSN, never defaults to Runtime DATABASE_URL."""
from datetime import datetime,timezone
import os
from uuid import uuid4
import pytest
from app.trace_store import Store

pytestmark=pytest.mark.skipif(not os.environ.get('TRACE_TEST_DSN'),reason='isolated PostgreSQL only')


def test_postgres_schema_identity_pagination_cutoff_and_business_isolation():
    a=Store('fixture-a',os.environ['TRACE_TEST_DSN']);b=Store('fixture-b',os.environ['TRACE_TEST_DSN'])
    stamp=int(datetime(2026,10,21,0,tzinfo=timezone.utc).timestamp()*1000)
    def row(camera,event):return dict(traceId=uuid4().hex,recordedAtMs=stamp,cameraId=camera,eventId=event,
                                     requestId=uuid4().hex,requestBody={'ordinary':True})
    a.write([row('00000003','e1'),row('5','e2')]);b.write([row('00000003','e3')])
    body={'server':'fixture-a','filters':{'camera':'00000003','from':'2026-10-21','to':'2026-10-21'}}
    plan=a.query('plan',body);assert plan['count']==1
    a.write([row('00000003','e4')])
    page=a.query('list',dict(body,cutoff=plan['cutoff']))
    assert len(page['rows'])==1 and 'requestBody' not in page['rows'][0]['doc']
    assert a.query('show',dict(body,seq=page['rows'][0]['seq']))['row']['doc']['requestBody']=={'ordinary':True}
    with pytest.raises(ValueError):a.query('clean',dict(plan,server='fixture-b',confirm='DELETE TRACE'))
    with pytest.raises(ValueError):a.query('clean',plan)
    deleted=a.query('clean',dict(plan,confirm='DELETE TRACE'));assert deleted['deleted']==1
    assert a.query('clean',dict(plan,confirm='DELETE TRACE'))['deleted']==0
    assert a.query('plan',body)['count']==1
    assert b.query('plan',dict(body,server='fixture-b'))['count']==1
    assert a.query('plan',{'server':'fixture-a','filters':{'camera':'5'}})['count']==1
    assert a.query('plan',{'server':'fixture-a','filters':{'camera':'3'}})['count']==0
    assert a.query('status',{'server':'fixture-a'})['autoCleanup'] is False
