import express from 'express';
import {
    createPredefinedActivity,
    getAllPredefinedActivities,
    getPredefinedActivityById,
    updatePredefinedActivity,
    searchPredefinedActivities,
    mergePredefinedActivities,
    deduplicatePredefinedActivities,
} from '../controllers/predefinedActivityController.js';
import multer from 'multer';
import { authenticate } from '../middleware/authMiddleware.js';
import { authorize } from '../middleware/authorizationMiddleware.js';
import { uploadPredefinedActivityImage, deletePredefinedActivityImage } from '../controllers/predefinedActivityImageController.js';
import PredefinedActivityImage from '../models/PredefinedActivityImage.js';
import path from 'path';
import fs from 'fs';
 
const router = express.Router();
const upload = multer({ storage: multer.memoryStorage() });

router.post('/', authenticate, createPredefinedActivity);
router.get('/', authenticate, getAllPredefinedActivities);
router.get('/search/query', authenticate, searchPredefinedActivities);
router.post('/merge', authenticate, mergePredefinedActivities);
router.post('/deduplicate', authenticate, deduplicatePredefinedActivities);
router.get('/:id', authenticate, getPredefinedActivityById);
router.put('/:id', authenticate, updatePredefinedActivity);
router.post('/:id/image', authenticate, upload.single('image'), uploadPredefinedActivityImage);
router.put('/:id/image', authenticate, upload.single('image'), uploadPredefinedActivityImage);
router.delete('/:id/image/:imageId', authenticate, deletePredefinedActivityImage);
router.get('/:id/image/:imageId', async (req, res) => {
  try {
    const { id, imageId } = req.params;
    const image = await PredefinedActivityImage.findOne({ where: { id: imageId, predefinedActivityId: id } });
    if (!image) return res.status(404).json({ error: 'Image not found' });
    if (!fs.existsSync(image.imagePath)) return res.status(404).json({ error: 'Image file missing' });
    res.sendFile(path.resolve(image.imagePath));
  } catch (e) {
    console.error('[getPredefinedActivityImage] - Error:', e);
    res.status(500).json({ error: 'Failed to fetch image' });
  }
});

export default router;
