/**
 * Fix Product sell_on_pos Field
 * Ensures all FG products have sell_on_pos=true and RM products have sell_on_pos=false
 * Run this script to fix existing products that may have incorrect sell_on_pos values
 */

require('dotenv').config();
const { sequelize, Product } = require('../models');

async function fixProductSellOnPos() {
  try {
    console.log('Starting product sell_on_pos fix...');
    
    // Connect to database
    await sequelize.authenticate();
    console.log('Database connected');
    
    // Find all products
    const products = await Product.findAll();
    console.log(`Found ${products.length} products to check`);
    
    let fixedCount = 0;
    let alreadyCorrectCount = 0;
    
    for (const product of products) {
      const expectedSellOnPos = product.product_type === 'FG';
      const currentSellOnPos = product.sell_on_pos;
      
      if (currentSellOnPos !== expectedSellOnPos) {
        await product.update({ sell_on_pos: expectedSellOnPos });
        console.log(`Fixed: Product ID ${product.id} (${product.name}) - ${product.product_type}: sell_on_pos changed from ${currentSellOnPos} to ${expectedSellOnPos}`);
        fixedCount++;
      } else {
        alreadyCorrectCount++;
      }
    }
    
    console.log('\n=== Fix Complete ===');
    console.log(`Total products: ${products.length}`);
    console.log(`Fixed: ${fixedCount}`);
    console.log(`Already correct: ${alreadyCorrectCount}`);
    
    // Close database connection
    await sequelize.close();
    console.log('\nDatabase connection closed');
    
  } catch (error) {
    console.error('Error fixing product sell_on_pos:', error);
    process.exit(1);
  }
}

// Run the fix
fixProductSellOnPos()
  .then(() => {
    console.log('\nDone!');
    process.exit(0);
  })
  .catch((error) => {
    console.error('Fatal error:', error);
    process.exit(1);
  });

