import dotenv from 'dotenv';
dotenv.config();

import mongoose from 'mongoose';
import Product from '../models/Product.js';
import { normalizeVariants, syncProductFromVariants } from './variantUtils.js';

const MEASUREMENT_UNITS = ['mg', 'g', 'kg', 'ml', 'L'];

const migrate = async () => {
  await mongoose.connect(process.env.MONGODB_URI);
  console.log('Connected to MongoDB');

  const products = await Product.find();
  let updated = 0;
  let skipped = 0;

  for (const product of products) {
    if (product.variants && product.variants.length > 0) {
      skipped += 1;
      continue;
    }

    const trackingType = product.trackingType || 'QUANTITY';
    let variants;

    if (trackingType === 'SIZE' && product.sizeVariants && product.sizeVariants.length > 0) {
      variants = product.sizeVariants.map((v) => ({
        label: v.size,
        size: v.size,
        measurementValue: null,
        measurementUnit: null,
        sellingUnit: product.unit || 'pcs',
        purchasePrice: product.purchasePrice || 0,
        sellingPrice: product.sellingPrice || 0,
        currentStock: v.stock || 0,
        lowStockThreshold: v.lowStockThreshold ?? product.lowStockThreshold ?? 10,
      }));
    } else {
      const unit = (product.unit || 'pcs').trim();
      const isMeasurement = MEASUREMENT_UNITS.includes(unit);
      variants = [
        {
          label: 'Standard',
          size: null,
          measurementValue: null,
          measurementUnit: isMeasurement ? unit : null,
          sellingUnit: isMeasurement ? 'pcs' : unit,
          purchasePrice: product.purchasePrice || 0,
          sellingPrice: product.sellingPrice || 0,
          currentStock: product.currentStock || 0,
          lowStockThreshold: product.lowStockThreshold ?? 10,
        },
      ];
    }

    product.variants = normalizeVariants(variants, { trackingType });
    syncProductFromVariants(product);
    await product.save();
    updated += 1;
    console.log(`Migrated: ${product.name} -> ${product.variants.length} variant(s)`);
  }

  console.log(`Done. Updated: ${updated}, Skipped (already migrated): ${skipped}`);
  await mongoose.disconnect();
  process.exit(0);
};

migrate().catch((err) => {
  console.error('Migration failed:', err.message);
  process.exit(1);
});