import Employee from '../model/Employee.js'
import GarageDetail from '../model/GarageDetails.js'
import User from '../model/User.js'

const addGarageDetail = async (req, res) => {
	try {
		const { countryId, stateId, cityId, picCode, fullAddress, garageType, gstNumber, userId } = req.body
		if (!countryId || !stateId || !cityId || !userId) return res.status(400).json({ message: 'Missing required fields' })
		// Prevent duplicate detail for same user (schema has unique on userId)
		const existing = await GarageDetail.findOne({ userId })
		if (existing) return res.status(400).json({ message: 'Garage details for this user already exist' })
		const detail = new GarageDetail({ countryId, stateId, cityId, picCode, fullAddress, garageType, gstNumber, userId })
		await detail.save()
		res.status(201).json({ message: 'Garage detail added', detail })
	} catch (err) {
		res.status(500).json({ message: 'Server error', error: err.message })
	}
}

const updateGarageDetail = async (req, res) => {
	try {
		const { id } = req.params
		const updates = req.body
		if (!id) return res.status(400).json({ message: 'Missing detail id in params' })
		const detail = await GarageDetail.findByIdAndUpdate(id, updates, { new: true })
		if (!detail) return res.status(404).json({ message: 'Garage detail not found' })
		res.json({ message: 'Garage detail updated', detail })
	} catch (err) {
		res.status(500).json({ message: 'Server error', error: err.message })
	}
}

const getGarageDetails = async (req, res) => {
	const userId = req.user.id
	try {
		const userData=await User.findById(userId)
		if(!userData) return res.status(404).json({ message: 'User not found' })

		const detail = await GarageDetail.findOne({ userId })
		
		return res.json({ detail, user: userData,success:true })
	} catch (err) {
		res.status(500).json({ message: 'Server error', error: err.message })
	}
}

const updateSettings = async (req, res) => {
	const userId = req.user?.id
	if (!userId) {
		return res.status(400).json({ message: 'User ID is required' })
	}
	try {
		const { garageName, ownerName, gst, phone, address, country, state, district, pincode } = req.body
		
		// Update user info
		let userData = await User.findById(userId)
		if (userData) {
			userData.garageName = garageName || userData.garageName
			userData.ownerName = ownerName || userData.ownerName
			await userData.save()
		}

		// Update or create garage detail
		let detail = await GarageDetail.findOne({ userId })
		if (!detail) {
			detail = new GarageDetail({ userId })
		}
		
		detail.country = country || detail.country
		detail.state = state || detail.state
		detail.district = district || detail.district
		detail.pincode = pincode || detail.pincode
		detail.address = address || detail.address
		detail.phone = phone || detail.phone
		detail.gst = gst || detail.gst
		
		if (req.file) {
			detail.logo = req.file.path.replace(/\\/g, "/")
		} else if (req.body.logo === null || req.body.logo === 'null') {
		    detail.logo = null
		}

		await detail.save()

		res.json({ message: 'Settings updated successfully', detail, user: userData, success: true })
	} catch (err) {
		res.status(500).json({ message: err?.message || 'Server error', error: err.message })
	}
}
const addEmployee = async (req, res) => {
	const userId = req.user?.id
	if (!userId) {
		return res.status(400).json({ message: 'User ID is required' })
	}
	try {
		const { name, mobileNumber, email, joinDate, salary, position, } = req.body
		if (!name || !mobileNumber || !email || !joinDate || !salary || !position || !userId) {
			return res.status(400).json({ message: 'Missing required fields' })
		}
		const employee = new Employee({ name, mobileNumber, email, joinDate, salary, position, userId })
		await employee.save()
		res.status(201).json({ message: 'Employee added', employee })
	} catch (err) {
		res.status(500).json({ message: err?.message || 'Server error', error: err.message })
	}
}
const updateEmployee = async (req, res) => {
	const userId = req.user?.id
	if (!userId) {
		return res.status(400).json({ message: 'User ID is required' })
	}
	try {
		const { name, mobileNumber, empId, email, joinDate, salary, position, status } = req.body
		if (!name || !mobileNumber || !email || !joinDate || !salary || !position || !userId) {
			return res.status(400).json({ message: 'Missing required fields' })
		}
		const employee = await Employee.findByIdAndUpdate(empId, { name, status, mobileNumber, email, joinDate, salary, position, userId }, { new: true })
		if (!employee) {
			return res.status(404).json({ message: 'Employee not found' })
		}
		res.json({ message: 'Employee updated', employee })
	} catch (err) {
		res.status(500).json({ message: err?.message || 'Server error', error: err.message })
	}
}
const getEmployees = async (req, res) => {
	const userId = req.user?.id
	if (!userId) {
		return res.status(400).json({ message: 'User ID is required' })
	}
	const { status, page = 1, limit = 10 } = req.query
	try {
		const employees = await Employee.find({ userId, status: "active" }).sort({ createdAt: -1 })
			.skip((page - 1) * limit).limit(parseInt(limit))
		const total = await Employee.countDocuments({ userId, status: "active" })
		res.json({
			count: employees.length,
			employees,
			totalPages: Math.ceil(total / limit),
			currentPage: parseInt(page)
		})
	} catch (err) {
		res.status(500).json({ message: err?.message || 'Server error', error: err.message })
	}
}
export default {
	addGarageDetail,
	updateGarageDetail,
	getGarageDetails,
	updateSettings,
	addEmployee,
	updateEmployee,
	getEmployees
}

