import Inventory from '../model/Inventory.js'

// Create - Add new inventory item
const addInventory = async (req, res) => {
	try {
		const userId=req.user.id
		const { name, purchasePrice, sellPrice, quantity,  } = req.body
		// Validationclg
		if (!name || purchasePrice === 0 || sellPrice === 0 || !userId) {
			return res.status(400).json({ success: false, message: 'Missing required fields: name, purchasePrice, sellPrice, userId' })
		}

		if (purchasePrice < 0 || sellPrice < 0) {
			return res.status(400).json({ success: false, message: 'Prices cannot be negative' })
		}

		if (quantity && quantity < 0) {
			return res.status(400).json({ success: false, message: 'Quantity cannot be negative' })
		}
		let stockPrice=quantity ? purchasePrice * quantity : 0

		const inventory = new Inventory({
			name,
			purchasePrice,
			sellPrice,
			quantity: quantity || 0,
			stockPrice,
			userId
		})

		await inventory.save()
		res.status(201).json({ success: true, message: 'Inventory item added successfully', inventory })
	} catch (err) {
		console.log(err)
		res.status(500).json({ success: false, message: 'Server error', error: err.message })
	}
}

// Read - Get all inventory items
const getAllInventory = async (req, res) => {
	try {
		const { userId, page = 1, limit = 10 } = req.query
		const skip = (page - 1) * limit

		let filter = {}
		if (userId) filter.userId = userId

		const total = await Inventory.countDocuments(filter)
		const inventory = await Inventory.find(filter)
			.populate('userId')
			.skip(skip)
			.limit(parseInt(limit))
			.sort({ createdAt: -1 })

		res.json({
			success: true,
			count: inventory.length,
			total,
			page: parseInt(page),
			pages: Math.ceil(total / limit),
			inventory
		})
	} catch (err) {
		res.status(500).json({ success: false, message: 'Server error', error: err.message })
	}
}

// Read - Get single inventory item by ID
const getInventoryById = async (req, res) => {
	try {
		const { id } = req.params

		if (!id) {
			return res.status(400).json({ success: false, message: 'Inventory ID is required' })
		}

		const inventory = await Inventory.findById(id).populate('userId')

		if (!inventory) {
			return res.status(404).json({ success: false, message: 'Inventory item not found' })
		}

		res.json({ success: true, inventory })
	} catch (err) {
		res.status(500).json({ success: false, message: 'Server error', error: err.message })
	}
}

// Read - Get inventory by userId
const getInventoryByUserId = async (req, res) => {
	try {
		const { userId } = req.params

		if (!userId) {
			return res.status(400).json({ success: false, message: 'User ID is required' })
		}

		const inventory = await Inventory.find({ userId }).populate('userId').sort({ createdAt: -1 })

		if (inventory.length === 0) {
			return res.status(404).json({ success: false, message: 'No inventory items found for this user' })
		}

		res.json({ success: true, count: inventory.length, inventory })
	} catch (err) {
		res.status(500).json({ success: false, message: 'Server error', error: err.message })
	}
}

// Update - Update inventory item
const updateInventory = async (req, res) => {
	try {
		const { _id :id} = req.body
		const updates = req.body

		if (!id) {
			return res.status(400).json({ success: false, message: 'Inventory ID is required' })
		}

		// Validate update data
		if (updates.purchasePrice !== undefined && updates.purchasePrice < 0) {
			return res.status(400).json({ success: false, message: 'Purchase price cannot be negative' })
		}

		if (updates.sellPrice !== undefined && updates.sellPrice < 0) {
			return res.status(400).json({ success: false, message: 'Sale price cannot be negative' })
		}

		if (updates.quantity !== undefined && updates.quantity < 0) {
			return res.status(400).json({ success: false, message: 'Quantity cannot be negative' })
		}

		const inventory = await Inventory.findByIdAndUpdate(id, updates, { new: true, runValidators: true }).populate('userId')

		if (!inventory) {
			return res.status(404).json({ success: false, message: 'Inventory item not found' })
		}

		res.json({ success: true, message: 'Inventory item updated successfully', inventory })
	} catch (err) {
		res.status(500).json({ success: false, message: 'Server error', error: err.message })
	}
}

// Update - Update stock (add or remove items)
const updateStock = async (req, res) => {
	try {
		const { id } = req.params
		const { quantity, operation } = req.body

		if (!id) {
			return res.status(400).json({ success: false, message: 'Inventory ID is required' })
		}

		if (quantity === undefined || !operation) {
			return res.status(400).json({ success: false, message: 'Quantity and operation (add/remove) are required' })
		}

		if (quantity < 0) {
			return res.status(400).json({ success: false, message: 'Quantity cannot be negative' })
		}

		if (!['add', 'remove'].includes(operation)) {
			return res.status(400).json({ success: false, message: 'Operation must be add or remove' })
		}

		const inventory = await Inventory.findById(id)
		if (!inventory) {
			return res.status(404).json({ success: false, message: 'Inventory item not found' })
		}

		let newQuantity = inventory.quantity

		if (operation === 'add') {
			newQuantity += quantity
		} else if (operation === 'remove') {
			newQuantity -= quantity
			if (newQuantity < 0) {
				return res.status(400).json({
					success: false,
					message: `Cannot remove ${quantity} units. Only ${inventory.quantity} units available`,
					currentStock: inventory.quantity
				})
			}
		}

		inventory.quantity = newQuantity
		await inventory.save()

		await inventory.populate('userId')

		res.json({
			success: true,
			message: `Stock ${operation}ed successfully`,
			inventory,
			currentStock: inventory.quantity
		})
	} catch (err) {
		res.status(500).json({ success: false, message: 'Server error', error: err.message })
	}
}

// Delete - Delete inventory item
const deleteInventory = async (req, res) => {
	try {
		const { id } = req.params

		if (!id) {
			return res.status(400).json({ success: false, message: 'Inventory ID is required' })
		}

		const inventory = await Inventory.findByIdAndDelete(id)

		if (!inventory) {
			return res.status(404).json({ success: false, message: 'Inventory item not found' })
		}

		res.json({ success: true, message: 'Inventory item deleted successfully', inventory })
	} catch (err) {
		res.status(500).json({ success: false, message: 'Server error', error: err.message })
	}
}

export default {
	addInventory,
	getAllInventory,
	getInventoryById,
	getInventoryByUserId,
	updateInventory,
	updateStock,
	deleteInventory
}
