import db from '../database/models/index.js';
const { User, Region, Zone } = db;
import bcrypt from 'bcryptjs';

async function verifyFix() {
    console.log('--- Starting UUID Sanitization Verification ---');
    
    const testEmail = `test_uuid_fix_${Date.now()}@example.com`;
    const password = await bcrypt.hash('Test@123', 10);

    try {
        // 1. Attempt to create a user with empty string for regionId
        // This simulates what the createUser controller now does after sanitization
        console.log('1. Testing User creation with empty-string sanitized to null...');
        
        const userData = {
            fullName: 'Test UUID User',
            email: testEmail,
            password: password,
            roleCode: 'ZBH',
            status: 'active',
            isActive: true,
            employeeId: `EMP-${Date.now()}`,
            mobileNumber: '1234567890',
            zoneId: null, // If frontend sends "", my controller now converts to null
            regionId: null, 
            stateId: null,
            districtId: null,
            areaId: null
        };

        const user = await User.create(userData);
        console.log('Success: User created with null UUID fields.');

        // 2. Simulate the Circular Dependency Workflow
        console.log('2. Testing Circular Dependency Workflow...');
        
        // a. Create a Zone first (needed for Region)
        const zone = await Zone.create({ 
            zoneCode: `ZNE-${Date.now().toString().slice(-4)}`,
            zoneName: `Test Zone ${Date.now()}` 
        });
        
        // b. Create a Region and assign the user as manager
        console.log('Creating Region with User as Manager...');
        const region = await Region.create({
            zoneId: zone.id,
            regionCode: `REG-${Date.now().toString().slice(-4)}`,
            regionName: 'Test Region',
            regionalManagerId: user.id
        });
        console.log('Success: Region created.');

        // c. Link User back to the Region
        console.log('Linking User back to the new Region...');
        await user.update({ regionId: region.id });
        console.log('Success: User updated with regionId.');

        // 3. Verify final state
        const updatedUser = await User.findByPk(user.id);
        if (updatedUser?.regionId === region.id) {
            console.log('VERIFICATION PASSED: User-Region cycle completed successfully.');
        } else {
            console.error('VERIFICATION FAILED: user.regionId was not updated correctly.');
        }

    } catch (error) {
        console.error('VERIFICATION FAILED with error:', error);
    } finally {
        process.exit();
    }
}

verifyFix();
