-- Read-only catalog inventory before applying tokenization migration.
-- No application rows or credentials are read. Counts are schema-object counts.
with expected(name) as (values
 ('tokenization_asset_types'),('tokenization_requests'),('tokenization_documents'),
 ('tokenization_internal_notes'),('tokenization_proposals'),
 ('tokenization_issuance_jobs'),('tokenization_allocation_ledger')
), objects as (
 select e.name,c.oid,c.relkind,c.relrowsecurity,
 (select count(*) from pg_attribute a where a.attrelid=c.oid and a.attnum>0 and not a.attisdropped) as column_count,
 (select count(*) from pg_constraint k where k.conrelid=c.oid and k.contype<>'n') as constraint_count
 from expected e left join pg_namespace n on n.nspname='marketplace_private'
 left join pg_class c on c.relnamespace=n.oid and c.relname=e.name
), functions as (
 select n.nspname as schema,p.oid::regprocedure::text as signature
 from pg_proc p join pg_namespace n on n.oid=p.pronamespace
 where (n.nspname='public' and p.proname like 'marketplace_tokenization_%')
    or (n.nspname='marketplace_private' and p.proname like 'tokenization_%')
)
select jsonb_build_object(
 'existing_target_tables',(select count(*) from objects where oid is not null),
 'target_metadata',(select jsonb_agg(jsonb_build_object('name',name,'exists',oid is not null,'kind',relkind,'rls',relrowsecurity,'columns',column_count,'constraints',constraint_count) order by name) from objects),
 'existing_public_functions',(select count(*) from functions where schema='public'),
 'existing_private_helpers',(select count(*) from functions where schema='marketplace_private'),
 'function_signatures_first_30',(select coalesce(jsonb_agg(signature order by signature),'[]') from (select signature from functions order by signature limit 30) f),
 'existing_named_indexes',(select coalesce(jsonb_agg(jsonb_build_object('name',indexname,'table',tablename) order by indexname),'[]') from pg_indexes
   where schemaname='marketplace_private' and indexname in('tokenization_owner_list','tokenization_admin_queue','tokenization_document_slot')),
 'existing_named_storage_policies',(select count(*) from pg_policies where schemaname='storage' and tablename='objects'
   and policyname in('tokenization_document_read','tokenization_document_insert','tokenization_document_delete')),
 'existing_private_bucket',(select count(*) from storage.buckets where id='tokenization-documents')
) as tokenization_preflight;
