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

const { RelocationRequest, Outlet, User, District, Region, Zone } = db;

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

    // 1. Find a test outlet
    const outlet = await Outlet.findOne({
      include: [
        {
          model: District,
          as: 'district',
          include: [
            { model: Region, as: 'region' },
            { model: Zone, as: 'zone' }
          ]
        }
      ]
    });

    if (!outlet || !outlet.district) {
      console.log('No outlet with district found to test.');
      process.exit(1);
    }

    console.log(`Testing with Outlet: ${outlet.code}, District: ${outlet.district.name}`);

    // Create a mock user if needed (the dealer)
    const dealer = await User.findOne({ where: { roleCode: 'Dealer' } });
    if (!dealer) {
        console.log('No dealer found for testing.');
        process.exit(1);
    }

    const { submitRequest } = await import('./src/modules/self-service/relocation.controller.js');
    
    // We'll mock the Request/Response if we wanted to call the controller directly, 
    // but here we just want to verify if the evaluator logic would work.
    
    // Let's just manually run the assignRelocationEvaluators logic (internal)
    // Actually, I'll just check if the Controller's getRequestById would return participants correctly.

    // Let's create a relocation request directly to test
    const request = await RelocationRequest.create({
      requestId: 'TEST-REL-' + Date.now(),
      outletId: outlet.id,
      dealerId: dealer.id,
      relocationType: 'Within City',
      newAddress: 'New Test Address',
      newCity: 'Test City',
      newState: 'Test State',
      reason: 'Testing workflow assignment',
      currentStage: RELOCATION_STAGES.ASM_REVIEW,
      status: 'Pending ASM Review',
      progressPercentage: 10,
      documents: [],
      timeline: []
    });

    console.log(`Created Test Request: ${request.requestId}`);

    // Now call the logic that calculates participants (similar to getRequestById)
    // We'll just look at the DB for now to see if NBH exists for the approval stage.
    // Check NBH
    const nbh = await User.findOne({ where: { roleCode: 'NBH', status: 'active' } });
    console.log(`NBH found in DB: ${nbh ? nbh.fullName : 'NO'}`);

    // Verify Evaluator Assignment Logic (Re-running a piece of it)
    const evaluators = [];
    evaluators.push({ id: outlet.district.asmId, role: 'ASM', stage: RELOCATION_STAGES.ASM_REVIEW });
    evaluators.push({ id: nbh?.id, role: 'NBH', stage: RELOCATION_STAGES.NBH_APPROVAL });

    console.log('Expected Evaluators for this request:');
    evaluators.forEach(e => console.log(`- Role: ${e.role}, Stage: ${e.stage}, ID: ${e.id}`));

    // Check for success: All must have IDs
    const missing = evaluators.filter(e => !e.id);
    if (missing.length > 0) {
      console.warn('WARNING: Missing some evaluators in the DB. Ensure they are seeded!');
      missing.forEach(m => console.log(`  Missing: ${m.role}`));
    } else {
      console.log('SUCCESS: All hierarchy and national evaluators identified.');
    }

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

run();
