import PredefinedActivity from '../models/PredefinedActivity.js';
import PredefinedActivityImage from '../models/PredefinedActivityImage.js';
import { checkGlobalAccess } from '../utils/userUtils.js';
import path from 'path';
import fs from 'fs';
import sharp from 'sharp';

import { devLog } from '../utils/logger.js';
export const uploadPredefinedActivityImage = async (req, res) => {
  try {
    const { id } = req.params; // predefinedActivityId
    const { authcode: userToken } = req.headers;
    await checkGlobalAccess(userToken); // Predefined Activities sind global, keine Club-Zugriffskontrolle nötig

    const activity = await PredefinedActivity.findByPk(id);
    if (!activity) {
      return res.status(404).json({ error: 'Predefined activity not found' });
    }

    if (!req.file || !req.file.buffer) {
      return res.status(400).json({ error: 'No image uploaded' });
    }

    const imagesDir = path.join('images', 'predefined');
    if (!fs.existsSync(imagesDir)) {
      fs.mkdirSync(imagesDir, { recursive: true });
    }

    const fileName = `${id}-${Date.now()}.jpg`;
    const filePath = path.join(imagesDir, fileName);

    await sharp(req.file.buffer)
      .resize(800, 800, { fit: 'inside' })
      .jpeg({ quality: 85 })
      .toFile(filePath);

    // Extrahiere Zeichnungsdaten aus dem Request
    const drawingData = req.body.drawingData ? JSON.parse(req.body.drawingData) : null;

    const imageRecord = await PredefinedActivityImage.create({
      predefinedActivityId: id,
      imagePath: filePath,
      mimeType: 'image/jpeg',
      drawingData: drawingData ? JSON.stringify(drawingData) : null,
    });

    // Optional: als imageLink am Activity-Datensatz setzen
    activity.imageLink = `/api/predefined-activities/${id}/image/${imageRecord.id}`;
    await activity.save();

    res.status(201).json({ id: imageRecord.id, imageLink: activity.imageLink });
  } catch (error) {
    console.error('[uploadPredefinedActivityImage] - Error:', error);
    res.status(500).json({ error: 'Failed to upload image' });
  }
};

export const deletePredefinedActivityImage = async (req, res) => {
  try {
    const { id, imageId } = req.params; // predefinedActivityId, imageId
    const { authcode: userToken } = req.headers;
    await checkGlobalAccess(userToken);

    const activity = await PredefinedActivity.findByPk(id);
    if (!activity) {
      return res.status(404).json({ error: 'Predefined activity not found' });
    }

    const image = await PredefinedActivityImage.findOne({ 
      where: { id: imageId, predefinedActivityId: id } 
    });
    if (!image) {
      return res.status(404).json({ error: 'Image not found' });
    }

    // Datei vom Dateisystem löschen
    if (fs.existsSync(image.imagePath)) {
      fs.unlinkSync(image.imagePath);
    }

    // Datensatz aus der Datenbank löschen
    await image.destroy();

    // Falls das gelöschte Bild der aktuelle imageLink war, diesen zurücksetzen
    if (activity.imageLink === `/api/predefined-activities/${id}/image/${imageId}`) {
      activity.imageLink = null;
      await activity.save();
    }

    res.status(200).json({ message: 'Image deleted successfully' });
  } catch (error) {
    console.error('[deletePredefinedActivityImage] - Error:', error);
    res.status(500).json({ error: 'Failed to delete image' });
  }
};


