const express = require('express');
const router = express.Router();
const sharp = require('sharp');
const fs = require('fs');
const dbTester = require('../test/tester');
const db = require('../db');
const serverError = require('../utils/serverError');

router.get('/smile', (req, res) => {
   const imagePath = dbTester.getSmileImage();
   fs.access(imagePath, fs.constants.F_OK, (err) => {
      if (err) {
         console.error('Image not found:', err);
         return res.status(404).json({ error: 'Image not found' });
      }
      res.sendFile(imagePath);
   });
});

router.get('/images/:projectId/:orderId', (req, res) => {
    const projectId = req.params.projectId;
    const orderId = req.params.orderId;
    const query = 'SELECT path FROM public.measurements WHERE project_id = $1 AND order_id = $2';
    db.query(query, [projectId, orderId], (err, results) => {
         if (err) {
             return serverError.sendError('Error getting image:', res, err, 500);
         }
         if (results.rows.length === 0) {
             return res.status(404).json({ error: 'Image not found' });
         }
         const imagePath = results.rows[0].path;
         fs.access(imagePath, fs.constants.F_OK, (err) => {
             if (err) {
                  console.error('Image not found:', err);
                  return res.status(404).json({ error: 'Image not found' });
             }
             res.download(imagePath);
         });
    });
});


router.get('/images/:measurementId', (req, res) => {
    const measurementId = req.params.measurementId;
    const query = 'SELECT path FROM public.measurements WHERE id = $1';
    db.query(query, [measurementId], (err, results) => {
        if (err) {
            return serverError.sendError('Error getting image:', res, err, 500);
        }
        if (results.rows.length === 0) {
            return res.status(404).json({ error: 'Image not found' });
        }
        const imagePath = results.rows[0].path;
        fs.access(imagePath, fs.constants.F_OK, (err) => {
            if (err) {
                console.error('Image not found:', err);
                return res.status(404).json({ error: 'Image not found' });
            }
            res.download(imagePath);
        });
    });
});

const getImagePath = async (projectId, orderId) => {
    const query = 'SELECT path FROM public.measurements WHERE project_id = $1 AND order_id = $2';
    const result = await db.query(query, [projectId, orderId]);
    if (result.rows.length === 0) {
        throw new Error('Image not found');
    }
    return result.rows[0].path;
};

const checkImageExists = (imagePath) => {
    return new Promise((resolve, reject) => {
        fs.access(imagePath, fs.constants.F_OK, (err) => {
            if (err) {
                reject(new Error('Image not found'));
            } else {
                resolve();
            }
        });
    });
};

const resizeImage = async (imagePath) => {
    const metadata = await sharp(imagePath).metadata();
    const width = Math.floor(metadata.width / 7);
    const height = Math.floor(metadata.height / 7);
    return sharp(imagePath)
        .resize(width, height)
        .jpeg({ quality: 65 })
        .toBuffer();
};

router.get('/preview/:projectId/:orderId', async (req, res) => {
    const projectId = req.params.projectId;
    const orderId = req.params.orderId;

    try {
        const imagePath = await getImagePath(projectId, orderId);
        await checkImageExists(imagePath);
        const resizedImage = await resizeImage(imagePath);

        res.set('Content-Type', 'image/jpeg');
        res.send(resizedImage);
    } catch (err) {
        console.error('Error getting image preview:', err);
        if (err.message === 'Image not found') {
            return res.status(404).json({ error: 'Image not found' });
        }
        return res.status(500).json({ error: 'Internal Server Error' });
    }
});

module.exports = router;
