const express = require('express');
const router = express.Router();
const models = require('../schemas/models');
const routes = require('./index');
const upload = require('../multer-config')


const Announcement = models.Announcement;
const isAuthenticated = routes.isAuthenticated;

// Route pour récupérer toutes les annonces
router.get('/', async (req, res) => {
    try {
        const announcements = await Announcement.find();
        let isAuthenticated = false;
        if (req.isAuthenticated()) {
            isAuthenticated = true;
        }
        console.log(req.user,'    ----------------------  ')
        res.render('announcements', { announcements: announcements, isAuthenticated: isAuthenticated , user : req.user},);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

// Route pour afficher la page d'ajout d'annonce
router.get('/add-announcement', isAuthenticated, (req, res) => {
    res.render('add_announcement',{ user : req.user });
});

// details de l'annonce
router.get('/:id', async (req, res) => {
    try {
        const announcementId = req.params.id;
        const announcementDetails = await Announcement.findById(announcementId);
        res.render('announcement_details', { announcement: announcementDetails ,user : req.user });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

router.post('/add-announcement', isAuthenticated, upload.array('photos', ), async (req, res) => {
    const { title, propertyType, publicationStatus, propertyStatus, description, price, availabilityDate} = req.body;
    const photos = req.files.map(file => file.filename);

    const user = req.user;

    const newAnnouncement = new Announcement({
        title,
        propertyType,
        publicationStatus,
        propertyStatus,
        description,
        price,
        availabilityDate,
        photos,
        userName: user.username
    });

    try {
        await newAnnouncement.save();
        const announcements = await Announcement.find();
        res.redirect('/announcements');
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

// route to display form to update an ad
router.get('/update/:id', isAuthenticated, async (req, res) => {
    try {
        const announcementId = req.params.id;
        const announcementDetails = await Announcement.findById(announcementId);

        if (!announcementDetails) {
            return res.status(404).json({ message: 'Announcement not found' });
        }

        res.render('update_announcement', { announcement: announcementDetails, user: req.user });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

// Route to handle update of an ad
router.post('/update/:id', isAuthenticated, upload.array('photos', ), async (req, res) => {
    console.log(req.body);
    const announcementId = req.params.id;
    const { title, propertyType, publicationStatus, propertyStatus, description, price, availabilityDate } = req.body;
    photos = [];
    if (req.files && req.files.length > 0) {
        photos = req.files.map(file => file.filename);
    }

    try {
        const updatedAnnouncement = await Announcement.findByIdAndUpdate(
            announcementId,
            {
                title,
                propertyType,
                publicationStatus,
                propertyStatus,
                description,
                price,
                availabilityDate,
                photos,
            },
            { new: true }
        );

        if (!updatedAnnouncement) {
            return res.status(404).json({ message: 'annonce non trouvée' });
        }

        res.redirect('/announcements');
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});



module.exports = router;
