<?php
declare(strict_types=1);
require __DIR__.'/ConfigWriteAudit.php';$runtime=tempnam(sys_get_temp_dir(),'cdx-address-audit-');unlink($runtime);mkdir($runtime,0700);
file_put_contents($runtime.'/private-owned-map.json',json_encode(['rows'=>['yoshop_store_address'=>['701'=>2147000821,'703'=>2147000822]]]));$audit=new ConfigWriteAudit($runtime,2147000821);
$tests=[
    ['values-own',"INSERT INTO yoshop_store_address (name,store_id) VALUES ('own',2147000821)",true],
    ['set-own',"INSERT INTO `yoshop_store_address` SET name='own',store_id=2147000821",true],
    ['scope-own',"UPDATE yoshop_store_address SET phone='00000000821' WHERE yoshop_store_address.store_id='2147000821' AND address_id=701",true],
    ['foreign-store',"INSERT INTO yoshop_store_address (store_id) VALUES (10001)",false],
    ['missing-owner',"INSERT INTO yoshop_store_address (name) VALUES ('own')",false],
    ['foreign-schema',"INSERT INTO other.yoshop_store_address (store_id) VALUES (2147000821)",false],
    ['fraction-owner',"INSERT INTO yoshop_store_address (store_id) VALUES (2147000821.1)",false],
    ['foreign-pk',"UPDATE yoshop_store_address SET sort=1 WHERE store_id=2147000821 AND address_id=702",false],
    ['other-tenant-owned-pk',"UPDATE yoshop_store_address SET sort=1 WHERE store_id=2147000821 AND address_id=703",false],
    ['batch-update-forbidden',"UPDATE yoshop_store_address SET sort=1 WHERE store_id=2147000821",false],
    ['or-widen',"UPDATE yoshop_store_address SET sort=1 WHERE store_id=2147000821 AND address_id=701 OR address_id=703",false],
    ['rekey',"UPDATE yoshop_store_address SET address_id=702 WHERE store_id=2147000821 AND address_id=701",false],
    ['retenant',"UPDATE yoshop_store_address SET store_id=10001 WHERE store_id=2147000821 AND address_id=701",false],
    ['region-write-forbidden',"UPDATE yoshop_region SET name='own' WHERE store_id=2147000821 AND address_id=701",false],
    ['user-address-write-forbidden',"UPDATE yoshop_user_address SET name='own' WHERE store_id=2147000821 AND address_id=701",false],
    ['delete-forbidden',"DELETE FROM yoshop_store_address WHERE address_id=701",false],
    ['multi-statement',"UPDATE yoshop_store_address SET sort=1 WHERE store_id=2147000821 AND address_id=701; DELETE FROM yoshop_region",false],
];$out=[];foreach($tests as [$name,$sql,$expected]){$ok=true;try{$audit->observe($sql);}catch(RuntimeException $e){$ok=false;}if($ok!==$expected)throw new RuntimeException('Missed address audit '.$name);$out[]=['case'=>$name,'accepted'=>$ok,'expected'=>$expected];}
echo json_encode(['assertions'=>count($out),'all_passed'=>true,'database_called'=>false,'cases'=>$out],JSON_PRETTY_PRINT),"\n";
foreach(['private-owned-map.json','private-write-sql.jsonl','write-audit.jsonl'] as $name)unlink($runtime.'/'.$name);rmdir($runtime);
