import Invoice from '../model/Invoice.js'
import Service from '../model/Service.js'

// Create - Add new service
const addService = async (req, res) => {
	const userId=req.user.id
	try {
		const { customerName, customerPhone, vehicleNumber, vehicleType, serviceType, status } = req.body
		console.log(req.body)
		// Validation
		if (!customerName || !customerPhone || !vehicleNumber || !userId) {
			return res.status(400).json({ success: false, message: 'Missing required fields: customerName, customerPhone, vehicleNumber, userId' })
		}

		const service = new Service({
			customerName,
			customerPhone,
			vehicleNumber,
			vehicleType: vehicleType || 'bike',
			serviceType: serviceType || 'repair',
			userId,
			status: status || 'pending'
		})

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

// Read - Get all services
const getAllServices = async (req, res) => {
	try {
		const { userId, status, vehicleType, page = 1, limit = 10 } = req.query
		const skip = (page - 1) * limit

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

		const total = await Service.countDocuments(filter)
		const services = await Service.find(filter).populate('invoiceId','finalAmount')
			.populate('userId')
			.skip(skip)
			.limit(parseInt(limit))
			.sort({ createdAt: -1 })

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

// Read - Get service by ID
const getServiceById = async (req, res) => {
	try {
		const { id } = req.params

		if (!id) {
			return res.status(400).json({ message: 'Service ID is required' })
		}

		const service = await Service.findById(id).populate('userId')

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

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

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

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

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

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

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

// Read - Get services by vehicle number
const getServiceByVehicleNumber = async (req, res) => {
	try {
		const { vehicleNumber } = req.params

		if (!vehicleNumber) {
			return res.status(400).json({ message: 'Vehicle number is required' })
		}

		const services = await Service.find({ vehicleNumber: vehicleNumber }).populate('userId').sort({ createdAt: -1 })

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

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

// Update - Update service details
const updateService = async (req, res) => {
	try {
		const { id } = req.params
		const updates = req.body

		if (!id) {
			return res.status(400).json({ message: 'Service ID is required' })
		}

		// Validate enum fields if provided
		if (updates.vehicleType && !['bike', 'car'].includes(updates.vehicleType)) {
			return res.status(400).json({ success: false, message: 'vehicleType must be bike or car' })
		}

		if (updates.serviceType && !['repair', 'maintenance', 'inspection'].includes(updates.serviceType)) {
			return res.status(400).json({ success: false, message: 'serviceType must be repair, maintenance, or inspection' })
		}

		if (updates.status && !['pending', 'in-progress', 'completed'].includes(updates.status)) {
			return res.status(400).json({ success: false, message: 'status must be pending, in-progress, or completed' })
		}

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

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

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

// Update - Update service status
const updateServiceStatus = async (req, res) => {
	try {
		const { id } = req.params
		const { status } = req.body

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

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

		if (!['pending', 'in-progress', 'ready','delivered'].includes(status)) {
			return res.status(400).json({ success: false, message: 'status must be pending, in-progress, ready, or delivered' })
		}

		const service = await Service.findByIdAndUpdate(id, { status }, { new: true }).populate('userId')

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

		res.json({ success: true, message: `Service status updated to ${status}`, service })
	} catch (err) {
		res.status(500).json({ success: false, message: 'Server error', error: err.message })
	}
}

// Delete - Delete service
const deleteService = async (req, res) => {
	try {
		const { id } = req.params

		if (!id) {
			return res.status(400).json({ message: 'Service ID is required' })
		}

		const service = await Service.findByIdAndDelete(id)

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

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

// Get services statistics
const getServiceStats = async (req, res) => {
	try {
		const { userId } = req.query

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

		const total = await Service.countDocuments(filter)
		const pending = await Service.countDocuments({ ...filter, status: 'pending' })
		const inProgress = await Service.countDocuments({ ...filter, status: 'in-progress' })
		const completed = await Service.countDocuments({ ...filter, status: 'completed' })

		res.json({
			success: true,
			statistics: {
				total,
				pending,
				inProgress,
				completed
			}
		})
	} catch (err) {
		res.status(500).json({ success: false, message: 'Server error', error: err.message })
	}
}

//			Invoice
const addInvoice = async (req, res) => {
	const userId=req.user.id
	try {
		const { serviceId,products,discountType,discountValue,subTotal,finalAmount } = req.body

		// Validation
		if (!serviceId || !subTotal || !finalAmount || !userId) {
			return res.status(400).json({ success: false, message: 'Missing required fields: service, subtotal, finalamount, userId' })
		}

		const invoice = new Invoice({
			serviceId,
			products,
			discountType,discountValue,subTotal,finalAmount,
			userId,
		})

		await invoice.save()
		await Service.findByIdAndUpdate(serviceId,{invoiceId:invoice._id},{new:true})
		res.status(201).json({ success: true, message: 'Invoice added successfully', invoice })
	} catch (err) {
		console.log(err)
		res.status(500).json({ success: false, message: 'Server error', error: err.message })
	}
}
const getServiceInvoice = async (req, res) => {
	const userId=req.user.id
	const serviceId=req.params.id
	try {
		const invoice=await Invoice.findOne({userId,serviceId})
		return res.status(201).json({ success: true, message: 'Invoice fetched successfully', invoice })
	} catch (err) {
		console.log(err)
		res.status(500).json({ success: false, message: 'Server error', error: err.message })
	}
}

export default {
	addService,
	getAllServices,
	getServiceById,
	getServiceByUserId,
	getServiceByVehicleNumber,
	updateService,
	updateServiceStatus,
	deleteService,
	getServiceStats,
	addInvoice,
	getServiceInvoice
}
