const generateId = require("shortid");
const express = require('express');
const { Router } = require('express');
const { endpoints, 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(endpoints.UPLOAD_STATIC_DIRECTORY, express.static( path.join(__dirname, '..', UPLOAD_FS_DIR) ));

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

router.post(endpoints.UPLOAD_FILE, async (req, res) => {
    if(req.files === null){
        console.log('No file uploaded');
        return res.status(400).json({ msg: 'No file uploaded' });
    }
    
    const file = req.files.file;
    const groupName = req.body.groupName || 'Unnamed Group';
    
    fileEnding = file.name.split(".")
    fileEnding = fileEnding[fileEnding.length - 1]
    fileName = generateId() + '.' + fileEnding
    
    const savePath = 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: `${endpoints.UPLOAD_STATIC_DIRECTORY}/${fileName}`,
                uploadOrder: 1,
                fileSize: fileSize,
                mimeType: file.mimetype,
                previewPath: `${endpoints.PREVIEW_STATIC_DIRECTORY}/${previewFileName}`
            }]
        };

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

        // Return immediately with file path
        res.json({ 
            filePath: `${endpoints.UPLOAD_STATIC_DIRECTORY}/${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;