<?php
/**
 * Prove the shim retires itself when the plugin ships its own capability.
 * Defines a stand-in for the 1.10.0 class, then re-asks every decision.
 */
function t( $l, $ok ) { echo ( $ok ? 'PASS  ' : 'FAIL !' ) . " $l\n"; }

// Before: 1.4.1 is installed, no BW_Lead_AI_Caps.
t( 'before: no native cap detected',        '' === bw_access_lead_ai_capability() );
t( 'before: lead-ai borrow IS registered',  isset( bw_access_proxy_screens()['bw-lead-ai'] ) );
$tools = bw_access_tools();
t( 'before: grant uses the stand-in name',  'bw_view_lead_ai' === $tools['lead_ai']['marker'] );
t( 'before: proxy flag on',                 ! empty( $tools['lead_ai']['proxy'] ) );

// Simulate the updated plugin.
if ( ! class_exists( 'BW_Lead_AI_Caps' ) ) {
	eval( 'class BW_Lead_AI_Caps { const VIEW = "bw_lead_ai_view"; public static function view() { return self::VIEW; } }' );
}

echo "\n--- plugin updated (BW_Lead_AI_Caps now present) ---\n";
t( 'after: native cap detected',            'bw_lead_ai_view' === bw_access_lead_ai_capability() );
t( 'after: lead-ai borrow NOT registered',  ! isset( bw_access_proxy_screens()['bw-lead-ai'] ) );
t( 'after: journey borrow NOT registered',  ! isset( bw_access_proxy_screens()['bw-lead-ai-journey'] ) );
t( 'after: guides borrow still registered', isset( bw_access_proxy_screens()['bw-guides'] ) );
$tools = bw_access_tools();
t( 'after: grant uses the REAL capability', 'bw_lead_ai_view' === $tools['lead_ai']['marker'] );
t( 'after: grant caps = the real one',      array( 'bw_lead_ai_view' ) === $tools['lead_ai']['caps'] );
t( 'after: proxy flag off',                 empty( $tools['lead_ai']['proxy'] ) );

// A grant made now must use the real name.
$u = get_user_by( 'login', 'bw_switch_probe' );
if ( ! $u ) {
	$u = get_userdata( wp_insert_user( array(
		'user_login' => 'bw_switch_probe',
		'user_pass'  => wp_generate_password( 32 ),
		'user_email' => 'bw-switch@example.invalid',
		'role'       => 'bw_staff',
	) ) );
}
bw_access_apply_submission( $u->ID, array( 'bw_tools' => array( 'lead_ai' => '1' ) ) );
$caps = get_userdata( $u->ID )->caps;
t( 'after: granting writes bw_lead_ai_view',   ! empty( $caps['bw_lead_ai_view'] ) );
t( 'after: does NOT write the stand-in name',  empty( $caps['bw_view_lead_ai'] ) );

// And revoking still works.
bw_access_apply_submission( $u->ID, array() );
$caps = get_userdata( $u->ID )->caps;
t( 'after: revoke removes the real cap',       empty( $caps['bw_lead_ai_view'] ) );

// The legacy-name migration.
$u2 = get_userdata( $u->ID );
$u2->add_cap( 'bw_view_lead_ai' );
delete_option( 'bw_access_lead_ai_migrated' );
do_action( 'admin_init' );
$caps = get_userdata( $u->ID )->caps;
t( 'migration: stand-in name upgraded to real', ! empty( $caps['bw_lead_ai_view'] ) && empty( $caps['bw_view_lead_ai'] ) );

wp_delete_user( $u->ID );
delete_option( 'bw_access_lead_ai_migrated' );
echo "\nprobe user deleted\n";
