// labourRoutes.js
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const labourController = require('../controllers/labourController');
const { protectLabour } = require('../middleware/authMiddleware'); // Import your middleware
const LabourType = require('../models/LabourType');
// Set up storage for uploaded files
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        // All uploaded images will now go into a single 'uploads/images/' directory.
        // Ensure this directory exists in your server root.
        cb(null, 'uploads/images/');
    },
    filename: (req, file, cb) => {
        // Generate a unique filename using timestamp and original extension
        cb(null, Date.now() + '-' + file.originalname);
    }
});

// Configure Multer to expect all three distinct file fields from the frontend.
// The 'name' property must exactly match the 'name' attribute in your React input
// or the key used in formData.append() on the frontend.
const upload = multer({ storage: storage }).fields([
    { name: 'profilePic', maxCount: 1 },      // Expects 'profilePic'
    { name: 'cnicPic', maxCount: 1 },         // Expects 'cnicPic'
    { name: 'policeCertPic', maxCount: 1 }    // Expects 'policeCertPic'
]);

// Route for labour registration, using the updated 'upload' middleware
router.post('/register', upload, labourController.register);

// Other routes remain the same
router.post('/login', labourController.login);
router.get('/all', labourController.getlabours);
router.post('/location', protectLabour, labourController.updateLocation); // <-- THIS IS KEY
router.get('/profile', protectLabour, labourController.getProfile); // Also protect the profile route
router.get('/nearby', labourController.getNearbyLabours);
router.post('/verify-email', labourController.verifyEmail);

// In your labour routes file
// ... your other routes like /login, /register ...
router.post('/forgot-password', labourController.forgotPassword);
router.post('/reset-password', labourController.resetPassword);

router.get('/labour-types', async (req, res) => {
    try {
        const types = await LabourType.find().sort({ name: 1 });
        // The frontend component just needs an array of names (strings)
        res.json(types.map(type => type.name)); 
    } catch (error) {
        console.error('Error fetching labour types for registration:', error);
        res.status(500).json({ message: 'Failed to fetch labour types.' });
    }
});

module.exports = router;



