import db from '../database/models/index.js';
const { User, Dealer, Outlet, Application, DealerCode } = db;

async function fixMissingOutlets() {
  try {
    console.log('--- Starting Missing Outlet Fix ---');
    
    // 1. Find all users with role 'Dealer'
    const dealerUsers = await User.findAll({
      where: { roleCode: 'Dealer' }
    });

    console.log(`Found ${dealerUsers.length} dealer users.`);

    for (const user of dealerUsers) {
      // 2. Check if this dealer already has an outlet
      const existingOutlet = await Outlet.findOne({ where: { dealerId: user.id } });
      
      if (existingOutlet) {
        console.log(`Dealer ${user.email} already has outlet: ${existingOutlet.code}. Skipping.`);
        continue;
      }

      console.log(`Dealer ${user.email} is missing an outlet. Attempting to create one...`);

      // 3. Find the dealer profile to get the application
      const dealerProfile = await Dealer.findOne({ where: { id: user.dealerId } });
      if (!dealerProfile) {
        console.warn(`Could not find dealer profile for user ${user.email}. Skipping.`);
        continue;
      }

      const application = await Application.findByPk(dealerProfile.applicationId);
      if (!application) {
        console.warn(`Could not find application for dealer ${user.email}. Skipping.`);
        continue;
      }

      // 4. Create the outlet (same logic as in dealer.controller.ts)
      const dealerCodeRecord = await DealerCode.findOne({ where: { applicationId: application.id } });
      const outletCode = `OUT-${dealerCodeRecord ? (dealerCodeRecord.dealerCode || dealerCodeRecord.code) : Date.now().toString().slice(-6)}`;

      const outlet = await Outlet.create({
        code: outletCode,
        name: `${application.applicantName} - ${application.city || 'Primary'}`,
        type: application.businessType === 'Studio' ? 'Studio' : 'Dealership',
        address: application.address || application.businessAddress || 'Address Pending',
        city: application.city || 'City Pending',
        state: application.state || 'State Pending',
        pincode: application.pincode || '000000',
        status: 'Active',
        establishedDate: new Date(),
        dealerId: user.id,
        region: 'Central', // Default fallback
        zone: 'National'
      });

      console.log(`Successfully created outlet ${outlet.code} for dealer ${user.email}.`);
    }

    console.log('--- Fix Completed ---');
    process.exit(0);
  } catch (error) {
    console.error('Error fixing missing outlets:', error);
    process.exit(1);
  }
}

fixMissingOutlets();
