const express = require('express');
const router = express.Router();
const multer = require('multer');
const database_manager = require('../src/database/database_manager');
const storage_manager = require('../src/data/storage_manager');
const serverError = require('../utils/serverError');

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

/**
 * @swagger
 * /camera/upload:
 *   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('/camera/upload', upload.single('image'), async (req, res) => {
  //afficher le body de la requête
  console.log(req.body);
  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 database_manager.measurement.get_next_order_id(projectId);
    if (nextOrderId === null) {
      return res.status(404).json({ error: 'Project not found' });
    }

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

    const imagePath = await storage_manager.measurement.upload_measurement_image(image, projectId, nextOrderId);
    if (!imagePath) {
      return res.status(500).json({ error: 'Failed to upload image' });
    }
    const measurement = await database_manager.measurement.create_measurement(projectId, timestamp, imagePath, temperature, humidity, nextOrderId);
    if (!measurement) {
      return res.status(500).json({ error: 'Failed to create measurement' });
    }
    res.json({ message: 'Measurement uploaded successfully', path: imagePath, id: measurement.id });
  } catch (error) {
    serverError.sendError('Error uploading measurement:', res, error, 500);
  }
});


module.exports = router;
