const asyncHandler = require('../middlewares/asyncHandler');
const {
  getAllCountries,
  getCountryById,
  createCountry,
  updateCountry,
  deleteCountry
} = require('../repositories/countryRepository');

// Get all countries
exports.getAllCountries = asyncHandler(async (req, res) => {
    const rows = await getAllCountries();
    res.status(200).json({ success: true, data: rows });
});

// Get country by ID
exports.getCountryById = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const country = await getCountryById(id);
    
    if (!country) {
        return res.status(404).json({ success: false, message: 'Country not found' });
    }
    
    res.status(200).json({ success: true, data: country });
});

// Create country
exports.createCountry = asyncHandler(async (req, res) => {
    const { country_id, country_name } = req.body;
    
    if (!country_id || !country_name) {
        return res.status(400).json({ success: false, message: 'country_id and country_name are required' });
    }
    
    await createCountry(country_id, country_name);
    res.status(201).json({ success: true, message: 'Country created successfully' });
});

// Update country
exports.updateCountry = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { country_name } = req.body;
    
    if (!country_name) {
        return res.status(400).json({ success: false, message: 'country_name is required' });
    }
    
    const updated = await updateCountry(id, country_name);
    
    if (!updated) {
        return res.status(404).json({ success: false, message: 'Country not found' });
    }
    
    res.status(200).json({ success: true, message: 'Country updated successfully' });
});

// Delete country
exports.deleteCountry = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const deleted = await deleteCountry(id);
    
    if (!deleted) {
        return res.status(404).json({ success: false, message: 'Country not found' });
    }
    
    res.status(200).json({ success: true, message: 'Country deleted successfully' });
});

