const express = require('express');
const router = express.Router();
const multer = require('multer');
const measureManager = require('../src/measure/measureManager');
const serverError = require('../utils/serverError');

const upload = multer({ storage: multer.memoryStorage() });

/**
 * @swagger
 * /uploadmeasurement:
 *   post:
 *     summary: Télécharger une mesure avec une image
 *     description: Télécharge une mesure avec une image pour un projet spécifique.
 *     requestBody:
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               image:
 *                 type: string
 *                 format: binary
 *                 description: Fichier image à télécharger
 *               projectId:
 *                 type: integer
 *                 description: ID du projet
 *               timestamp:
 *                 type: string
 *                 format: date-time
 *                 description: Horodatage de la mesure
 *               temperature:
 *                 type: number
 *                 description: Température mesurée
 *               humidity:
 *                 type: number
 *                 description: Humidité mesurée
 *     responses:
 *       200:
 *         description: Mesure téléchargée avec succès.
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                 path:
 *                   type: string
 *                 id:
 *                   type: integer
 *       400:
 *         description: Tous les champs sont requis.
 *       500:
 *         description: Erreur serveur.
 */
router.post('/uploadmeasurement', upload.single('image'), async (req, res) => {
  const { projectId, timestamp, temperature, humidity } = req.body;
  const image = req.file;

  if (!image || !projectId || !timestamp || !temperature || !humidity) {
    return res.status(400).json({ error: 'All fields are required' });
  }

  try {
    const nextOrderId = await measureManager.getNextOrderId(projectId);

    // Log types for debugging
    console.log('Types:', {
      image: typeof image,
      projectId: typeof projectId,
      nextOrderId: typeof nextOrderId
    });

    const imagePath = await measureManager.uploadMeasureImage(image, projectId, nextOrderId);
    const measurement = await measureManager.addMeasureToProject(projectId, timestamp, imagePath, temperature, humidity, nextOrderId);
    res.json({ message: 'Measurement uploaded successfully', path: imagePath, id: measurement.id });
  } catch (error) {
    console.error('Error uploading measurement:', error);
    serverError.sendError('Error uploading measurement:', res, error);
  }
});


module.exports = router;
