const Company = require('../models/Company');

// Get all companies
exports.getCompanies = async (req, res) => {
  try {
   
    const companies = await Company.find();
    res.status(200).json(companies);
  } catch (error) {
    res.status(500).json({ message: 'Server error' });
  }
};


exports.getCompany = async (req, res) => {
  try {
   const companyId=req.query.companyId;
 
    const company = await Company.findOne({_id:companyId});
    res.status(200).json(company);
 
  } catch (error) {
    res.status(500).json({ message: 'Server error' });
  }
};
// Add a new company
// Improved error handling in companyController.js

exports.createCompany = async (req, res) => {
  const { name } = req.body;

  try {
    if (!name) {
      return res.status(400).json({ message: 'Company name is required' });
    }
    const newCompany = new Company({ name });
    await newCompany.save();
    res.status(201).json(newCompany);
  } catch (error) {
    console.error('Error creating company:', error.message);  // Log the error
    res.status(500).json({ message: 'Server error', error: error.message });  // Send more details to the client
  }
};


// Update a company by ID

// Update a company by ID
exports.updateCompany = async (req, res) => {
  const { name,shopType } = req.body;

  // Prepare the update object
  const updateFields = { name ,shopType};

  // If an image is uploaded, add the profile_url field to the update
  if (req.file) {
    updateFields.profile_url = `/uploads/${req.file.filename}`;
  }

  try {
    const company = await Company.findByIdAndUpdate(req.params.id, updateFields, { new: true });
    
    if (!company) {
      return res.status(404).json({ message: 'Company not found' });
    }

    res.status(200).json(company);
  } catch (error) {
    res.status(500).json({ message: 'Server error' });
  }
};





// Delete a company by ID
exports.deleteCompany = async (req, res) => {
  try {
    const company = await Company.findByIdAndDelete(req.params.id);
    if (!company) {
      return res.status(404).json({ message: 'Company not found' });
    }
    res.status(200).json({ message: 'Company deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: 'Server error' });
  }
};
