const generateId = require("shortid");
const express = require('express');
const { Router } = require('express');
const { UPLOAD_FS_DIR, PREVIEW_FS_DIR } = require('../constants');
const path = require('path');
const ImagePreviewService = require('../services/ImagePreviewService');
const groupRepository = require('../repositories/GroupRepository');
const fs = require('fs');

const router = Router();

// Serve uploaded images via URL /upload but store files under data/images
router.use('/upload', express.static( path.join(__dirname, '..', UPLOAD_FS_DIR) ));

// Serve preview images via URL /previews but store files under data/previews
router.use('/previews', express.static( path.join(__dirname, '..', PREVIEW_FS_DIR) ));

router.post('/upload', async (req, res) => {
    /* 
        #swagger.tags = ['Upload']
        #swagger.summary = 'Upload a single image and create a new group'
        #swagger.description = 'Uploads an image file, generates a preview, and creates a new group in the database'
        #swagger.consumes = ['multipart/form-data']
        #swagger.parameters['file'] = {
            in: 'formData',
            type: 'file',
            required: true,
            description: 'Image file to upload'
        }
        #swagger.parameters['groupName'] = {
            in: 'formData',
            type: 'string',
            description: 'Name for the new group',
            example: 'Familie Mueller'
        }
        #swagger.responses[200] = {
            description: 'File uploaded successfully',
            schema: {
                filePath: '/upload/abc123.jpg',
                fileName: 'abc123.jpg',
                groupId: 'cTV24Yn-a',
                groupName: 'Familie Mueller'
            }
        }
        #swagger.responses[400] = {
            description: 'No file uploaded',
            schema: { msg: 'No file uploaded' }
        }
        #swagger.responses[500] = {
            description: 'Server error during upload'
        }
    */
    if(!req.files || req.files === null || !req.files.file){
        console.log('No file uploaded');
        return res.status(400).json({ error: 'Keine Datei hochgeladen' });
    }
    
    const file = req.files.file;
    const groupName = req.body.groupName || 'Unnamed Group';
    
    fileEnding = file.name.split(".")
    fileEnding = fileEnding[fileEnding.length - 1]
    fileName = generateId() + '.' + fileEnding
    
    // Handle absolute vs relative paths (test mode uses /tmp)
    const savePath = path.isAbsolute(UPLOAD_FS_DIR)
        ? path.join(UPLOAD_FS_DIR, fileName)
        : path.join(__dirname, '..', UPLOAD_FS_DIR, fileName);
    
    try {
        // Save the uploaded file
        await new Promise((resolve, reject) => {
            file.mv(savePath, err => {
                if(err) reject(err);
                else resolve();
            });
        });

        // Get file stats
        const fileStats = fs.statSync(savePath);
        const fileSize = fileStats.size;

        // Generate preview asynchronously (don't wait for it)
        const previewFileName = ImagePreviewService._getPreviewFileName(fileName);
        const previewPath = ImagePreviewService.getPreviewPath(previewFileName);
        
        ImagePreviewService.generatePreview(savePath, previewPath)
            .then(result => {
                if (!result.success) {
                    console.warn(`Preview generation failed for ${fileName}:`, result.error);
                }
            })
            .catch(err => {
                console.error(`Unexpected error during preview generation for ${fileName}:`, err);
            });

        // Create or update group in database
        const groupId = generateId();
        const currentYear = new Date().getFullYear();
        const uploadDate = new Date().toISOString();

        const groupData = {
            groupId: groupId,
            year: currentYear,
            title: groupName,
            description: `Einzelnes Bild Upload: ${file.name}`,
            name: groupName,
            uploadDate: uploadDate,
            images: [{
                fileName: fileName,
                originalName: file.name,
                filePath: `/upload/${fileName}`,
                uploadOrder: 1,
                fileSize: fileSize,
                mimeType: file.mimetype,
                previewPath: `/previews/${previewFileName}`
            }]
        };

        // Save to database
        await groupRepository.createGroup(groupData);
        
        console.log(`✅ Group created: ${groupName} with image ${fileName}`);

        // Return immediately with file path
        res.json({ 
            filePath: `/upload/${fileName}`,
            fileName: fileName,
            groupId: groupId,
            groupName: groupName
        });
        
    } catch(err) {
        console.error('Upload error:', err);
        return res.status(500).json({ error: err.message });
    }
});

module.exports = router;