const mongoose = require('mongoose');

// Controller to get all collection names
exports.getCollections = async (req, res) => {
  try {
    const collections = await mongoose.connection.db.listCollections().toArray();
    const collectionNames = collections.map(c => c.name);
    res.status(200).json(collectionNames);
  } catch (error) {
    console.error('Error fetching collections:', error);
    res.status(500).json({ message: 'Failed to fetch collections' });
  }
};

// Controller to get all companies
exports.getCompanies = async (req, res) => {
  try {
    const companies = await mongoose.connection.db.collection('companies').find({}).toArray();
    res.status(200).json(companies);
  } catch (error) {
    console.error('Error fetching companies:', error);
    res.status(500).json({ message: 'Failed to fetch companies' });
  }
};

// Controller to delete selected collections for a specific company
exports.deleteSelectedCollections = async (req, res) => {
  const { collections, companyId } = req.body;

  if (!collections || !Array.isArray(collections) || collections.length === 0) {
    return res.status(400).json({ message: 'No collections selected for deletion' });
  }

  if (!companyId) {
    return res.status(400).json({ message: 'Company ID is required for deletion.' });
  }

  try { const objectId = new mongoose.Types.ObjectId(companyId);  // Ensure proper instantiation

    // Loop through the selected collections and delete records with the given companyId
    for (const collection of collections) {
      const result = await mongoose.connection.db.collection(collection).deleteMany({ companyId: objectId });
      console.log(`Deleted ${result.deletedCount} records from ${collection} collection`);
    }
    res.status(200).json({ message: 'Selected collections have been cleared for the specified company ID.' });
  } catch (error) {
    console.error('Error deleting collections:', error);
    res.status(500).json({ message: 'Failed to delete selected collections by company ID' });
  }
};
