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

// Get all taxes with pagination and search
const getAllTaxes = async (req, res) => {
  try {
    const { page = 1, limit = 10, search = '' } = req.query;
    
    const options = {
      page: parseInt(page),
      limit: parseInt(limit),
      search: search.trim()
    };

    const result = await Tax.findAllActive(options);
    
    res.json({
      success: true,
      data: result.items,
      pagination: {
        currentPage: result.currentPage,
        totalPages: result.totalPages,
        totalItems: result.total,
        hasNextPage: result.hasNextPage,
        hasPrevPage: result.hasPrevPage
      },
      msg: 'Taxes retrieved successfully'
    });
  } catch (error) {
    console.error('Error fetching taxes:', error);
    res.status(500).json({
      success: false,
      msg: error.message || 'Error fetching taxes'
    });
  }
};

// Get tax by ID with item count
const getTaxById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const tax = await Tax.findByIdWithDetails(id);
    
    if (!tax) {
      return res.status(404).json({
        success: false,
        msg: 'Tax not found'
      });
    }
    
    res.json({
      success: true,
      data: tax,
      msg: 'Tax retrieved successfully'
    });
  } catch (error) {
    console.error('Error fetching tax:', error);
    res.status(500).json({
      success: false,
      msg: error.message || 'Error fetching tax'
    });
  }
};

// Create new tax
const createTax = async (req, res) => {
  try {
    const { name, percentage } = req.body;
    
    // Validation
    if (!name || !name.trim()) {
      return res.status(400).json({
        success: false,
        msg: 'Tax name is required'
      });
    }

    if (percentage === undefined || percentage === null) {
      return res.status(400).json({
        success: false,
        msg: 'Tax percentage is required'
      });
    }

    const newTax = await Tax.createTax({
      name,
      percentage
    });

    res.status(201).json({
      success: true,
      data: newTax,
      msg: 'Tax created successfully'
    });
  } catch (error) {
    console.error('Error creating tax:', error);
    
    // Handle specific validation errors
    if (error.message.includes('already exists')) {
      return res.status(409).json({
        success: false,
        msg: error.message
      });
    }
    
    if (error.name === 'ValidationError') {
      const validationErrors = Object.values(error.errors).map(err => err.message);
      return res.status(400).json({
        success: false,
        msg: 'Validation failed',
        errors: validationErrors
      });
    }

    res.status(500).json({
      success: false,
      msg: error.message || 'Error creating tax'
    });
  }
};

// Update tax
const updateTax = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, percentage, status } = req.body;
    
    // Check if tax exists
    const existingTax = await Tax.findById(id);
    if (!existingTax) {
      return res.status(404).json({
        success: false,
        msg: 'Tax not found'
      });
    }

    const updateData = {
      name,
      percentage,
      status
    };

    const updatedTax = await Tax.update(id, updateData, { runValidators: true });

    res.json({
      success: true,
      data: updatedTax,
      msg: 'Tax updated successfully'
    });
  } catch (error) {
    console.error('Error updating tax:', error);

    // Handle specific validation errors
    if (error.message.includes('already exists')) {
      return res.status(409).json({
        success: false,
        msg: error.message
      });
    }
    
    if (error.name === 'ValidationError') {
      const validationErrors = Object.values(error.errors).map(err => err.message);
      return res.status(400).json({
        success: false,
        msg: 'Validation failed',
        errors: validationErrors
      });
    }

    res.status(500).json({
      success: false,
      msg: error.message || 'Error updating tax'
    });
  }
};

// Toggle tax status
const toggleTaxStatus = async (req, res) => {
  try {
    const { id } = req.params;
    
    // Find the tax first
    const tax = await Tax.findOne({ _id: id });
    if (!tax) {
      return res.status(404).json({
        success: false,
        msg: 'Tax not found'
      });
    }

    // Toggle the status
    tax.status = !tax.status;
    
    // Save the updated tax
    const updatedTax = await tax.save();
    
    res.json({
      success: true,
      data: updatedTax,
      msg: `Tax ${updatedTax.status ? 'activated' : 'deactivated'} successfully`
    });
  } catch (error) {
    console.error('Error toggling tax status:', error);
    
    if (error.message.includes('not found')) {
      return res.status(404).json({
        success: false,
        msg: error.message
      });
    }

    res.status(500).json({
      success: false,
      msg: error.message || 'Error toggling tax status'
    });
  }
};

// Delete tax (hard delete)
const deleteTax = async (req, res) => {
  try {
    const { id } = req.params;
    
    // Check if tax exists
    const existingTax = await Tax.findById(id);
    if (!existingTax) {
      return res.status(404).json({
        success: false,
        msg: 'Tax not found'
      });
    }

    // Check if tax is being used by any items
    const taxWithDetails = await Tax.findByIdWithDetails(id);
    if (taxWithDetails && taxWithDetails.itemCount > 0) {
      return res.status(400).json({
        success: false,
        msg: `Cannot delete tax. It is being used by ${taxWithDetails.itemCount} item(s). Please remove the tax from all items first.`
      });
    }

    await Tax.deleteTax(id);
    
    res.json({
      success: true,
      msg: 'Tax deleted successfully'
    });
  } catch (error) {
    console.error('Error deleting tax:', error);
    res.status(500).json({
      success: false,
      msg: error.message || 'Error deleting tax'
    });
  }
};

// Get active taxes for dropdown
const getActiveTaxes = async (req, res) => {
  try {
    const taxes = await Tax.getActiveTaxes();
    
    res.json({
      success: true,
      data: taxes,
      msg: 'Active taxes retrieved successfully'
    });
  } catch (error) {
    console.error('Error fetching active taxes:', error);
    res.status(500).json({
      success: false,
      msg: error.message || 'Error fetching active taxes'
    });
  }
};

// Get tax statistics
const getTaxStatistics = async (req, res) => {
  try {
    const statistics = await Tax.getStatistics();
    
    res.json({
      success: true,
      data: statistics,
      msg: 'Tax statistics retrieved successfully'
    });
  } catch (error) {
    console.error('Error fetching tax statistics:', error);
    res.status(500).json({
      success: false,
      msg: error.message || 'Error fetching tax statistics'
    });
  }
};

// Search taxes
const searchTaxes = async (req, res) => {
  try {
    const { q: query, page = 1, limit = 10 } = req.query;
    
    if (!query || !query.trim()) {
      return res.status(400).json({
        success: false,
        msg: 'Search query is required'
      });
    }

    const result = await Tax.searchTaxes(query.trim(), parseInt(page), parseInt(limit));
    
    res.json({
      success: true,
      data: result.items,
      pagination: {
        currentPage: result.currentPage,
        totalPages: result.totalPages,
        totalItems: result.total,
        hasNextPage: result.hasNextPage,
        hasPrevPage: result.hasPrevPage
      },
      msg: 'Search results retrieved successfully'
    });
  } catch (error) {
    console.error('Error searching taxes:', error);
    res.status(500).json({
      success: false,
      msg: error.message || 'Error searching taxes'
    });
  }
};

module.exports = {
  getAllTaxes,
  getTaxById,
  createTax,
  updateTax,
  toggleTaxStatus,
  deleteTax,
  getActiveTaxes,
  getTaxStatistics,
  searchTaxes
}; 