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

// Get all units with pagination and search
const getAllUnits = async (req, res) => {
  try {
    const {
      page = 1,
      limit = 10,
      search,
      sortBy = 'createdAt',
      sortOrder = 'desc'
    } = req.query;

    const options = {
      page: parseInt(page),
      limit: parseInt(limit),
      search: search || undefined
    };

    const result = await Unit.findAllActive(options);

    res.json({
      success: true,
      data: result.items,
      pagination: {
        currentPage: result.currentPage,
        totalPages: result.totalPages,
        totalUnits: result.total,
        hasNextPage: result.hasNextPage,
        hasPreviousPage: result.hasPreviousPage
      },
      msg: 'Units retrieved successfully'
    });
  } catch (error) {
    console.error('Error fetching units:', error);
    res.status(500).json({
      success: false,
      msg: error.message || 'Error fetching units'
    });
  }
};

// Get unit by ID with details
const getUnitById = async (req, res) => {
  try {
    const { id } = req.params;
    
    // Validate ID format
    if (!id || !/^[0-9a-fA-F]{24}$/.test(id)) {
      return res.status(400).json({
        success: false,
        msg: 'Invalid unit ID format'
      });
    }
    
    const unit = await Unit.findByIdWithDetails(id);
    
    if (!unit) {
      return res.status(404).json({
        success: false,
        msg: 'Unit not found'
      });
    }
    
    res.json({
      success: true,
      data: unit,
      msg: 'Unit retrieved successfully'
    });
  } catch (error) {
    console.error('Error fetching unit:', error);
    
    // Handle specific error types
    if (error.name === 'CastError') {
      return res.status(400).json({
        success: false,
        msg: 'Invalid unit ID format'
      });
    }
    
    res.status(500).json({
      success: false,
      msg: 'Error fetching unit details',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// Create new unit
const createUnit = async (req, res) => {
  try {
    const { name, short_code, remark } = req.body;
    
    // Validation
    if (!name || !name.trim()) {
      return res.status(400).json({
        success: false,
        msg: 'Unit name is required'
      });
    }

    const newUnit = await Unit.createUnit({
      name,
      short_code,
      remark
    });

    res.status(201).json({
      success: true,
      data: newUnit,
      msg: 'Unit created successfully'
    });
  } catch (error) {
    console.error('Error creating unit:', error);

    // Handle specific validation errors
    if (error.message === 'Unit name already exists' || error.message === 'Unit short code already exists') {
      return res.status(409).json({
        success: false,
        msg: error.message
      });
    }

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

// Update unit
const updateUnit = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, short_code, remark, status } = req.body;
    
    // Check if unit exists
    const existingUnit = await Unit.findById(id);
    if (!existingUnit) {
      return res.status(404).json({
        success: false,
        msg: 'Unit not found'
      });
    }

    const updateData = {
      name,
      short_code,
      remark,
      status
    };

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

    res.json({
      success: true,
      data: updatedUnit,
      msg: 'Unit updated successfully'
    });
  } catch (error) {
    console.error('Error updating unit:', error);

    // Handle specific validation errors
    if (error.message === 'Unit name already exists' || error.message === 'Unit short code already exists') {
      return res.status(409).json({
        success: false,
        msg: error.message
      });
    }

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

// Toggle unit status
const toggleUnitStatus = async (req, res) => {
  try {
    const { id } = req.params;

    // Check if unit exists
    const existingUnit = await Unit.findById(id);
    if (!existingUnit) {
      return res.status(404).json({
        success: false,
        msg: 'Unit not found'
      });
    }

    const updatedUnit = await Unit.findByIdAndUpdate(
      id,
      { status: !existingUnit.status },
      { new: true }
    );

    res.json({
      success: true,
      data: updatedUnit,
      msg: `Unit ${updatedUnit.status ? 'activated' : 'deactivated'} successfully`
    });
  } catch (error) {
    console.error('Error toggling unit status:', error);
    res.status(500).json({
      success: false,
      msg: error.message || 'Error toggling unit status'
    });
  }
};

// Permanently delete unit (hard delete)
const deleteUnit = async (req, res) => {
  try {
    const { id } = req.params;
    
    // Check if unit exists
    const existingUnit = await Unit.findById(id);
    if (!existingUnit) {
      return res.status(404).json({
        success: false,
        msg: 'Unit not found'
      });
    }

    // Check if unit has associated items
    const itemsWithUnit = await Unit.findByIdWithDetails(id);
    if (itemsWithUnit && itemsWithUnit.itemCount > 0) {
      return res.status(400).json({
        success: false,
        msg: `Cannot delete unit with ${itemsWithUnit.itemCount} associated items. Please delete all items first or reassign them to another unit.`
      });
    }

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

// Get unit statistics
const getUnitStatistics = async (req, res) => {
  try {
    const statistics = await Unit.getStatistics();

    res.json({
      success: true,
      data: statistics,
      msg: 'Unit statistics retrieved successfully'
    });
  } catch (error) {
    console.error('Error fetching unit statistics:', error);
    res.status(500).json({
      success: false,
      msg: error.message || 'Error fetching unit statistics'
    });
  }
};

// Search units
const searchUnits = async (req, res) => {
  try {
    const { query, limit = 10 } = req.query;

    if (!query) {
      return res.status(400).json({
        success: false,
        msg: 'Search query is required'
      });
    }

    const units = await Unit.findAllActive({
      search: query,
      limit: parseInt(limit),
      page: 1
    });

    res.json({
      success: true,
      data: units.items,
      total: units.total,
      msg: 'Search completed successfully'
    });
  } catch (error) {
    console.error('Error searching units:', error);
    res.status(500).json({
      success: false,
      msg: error.message || 'Error searching units'
    });
  }
};

module.exports = {
  getAllUnits,
  getUnitById,
  createUnit,
  updateUnit,
  toggleUnitStatus,
  deleteUnit,
  getUnitStatistics,
  searchUnits
}; 