import db from './src/database/models/index.js';
import { RELOCATION_STAGES, ROLES } from './src/common/config/constants.js';
import { RelocationWorkflowService } from './src/services/RelocationWorkflowService.js';

const { RelocationRequest, User } = db;

async function run() {
  try {
    console.log('--- Relocation Authorization Verification ---');

    // 1. Find a test request
    const request = await RelocationRequest.findOne({
        order: [['createdAt', 'DESC']]
    });

    if (!request) {
      console.log('No relocation request found to test.');
      process.exit(0);
    }

    console.log(`Testing Request: ${request.requestId}, Current Stage: ${request.currentStage}`);

    // 2. Find users with different roles
    const asmUser = await User.findOne({ where: { roleCode: ROLES.ASM, status: 'active' } });
    const rbmUser = await User.findOne({ where: { roleCode: ROLES.RBM, status: 'active' } });
    const dealerUser = await User.findOne({ where: { roleCode: ROLES.DEALER, status: 'active' } });
    const superAdmin = await User.findOne({ where: { roleCode: ROLES.SUPER_ADMIN, status: 'active' } });

    // 3. Test ASM approval on ASM_REVIEW stage
    if (request.currentStage === RELOCATION_STAGES.ASM_REVIEW) {
        console.log('Testing ASM_REVIEW stage:');
        
        const canASM = await RelocationWorkflowService.canUserAction(request, asmUser);
        console.log(`- ASM can action: ${canASM} (Expected: true)`);

        const canRBM = await RelocationWorkflowService.canUserAction(request, rbmUser);
        console.log(`- RBM can action: ${canRBM} (Expected: false)`);

        const canDealer = await RelocationWorkflowService.canUserAction(request, dealerUser);
        console.log(`- Dealer can action: ${canDealer} (Expected: false)`);

        const canSuperAdmin = await RelocationWorkflowService.canUserAction(request, superAdmin);
        console.log(`- Super Admin can action: ${canSuperAdmin} (Expected: true)`);
    } else {
        console.log(`Request is in ${request.currentStage}. Please create a new request to test ASM_REVIEW.`);
    }

    process.exit(0);
  } catch (error) {
    console.error(error);
    process.exit(1);
  }
}

run();
