const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const cors = require('cors');

const app = express();
const PORT = 3000;

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('src'));
app.use('/public', express.static('public'));

// Configure multer for video upload
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadDir = path.join(__dirname, '../public');
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true });
        }
        cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
        // Generate unique filename with timestamp
        const timestamp = Date.now();
        const ext = path.extname(file.originalname);
        const nameWithoutExt = path.basename(file.originalname, ext);
        const sanitizedName = nameWithoutExt.replace(/[^a-zA-Z0-9]/g, '_');
        cb(null, `${sanitizedName}_${timestamp}${ext}`);
    }
});

const upload = multer({
    storage: storage,
    fileFilter: function (req, file, cb) {
        // Accept video files only
        if (file.mimetype.startsWith('video/')) {
            cb(null, true);
        } else {
            cb(new Error('Only video files are allowed!'), false);
        }
    },
    limits: {
        fileSize: 500 * 1024 * 1024 // 500MB limit
    }
});

// Upload endpoint
app.post('/upload', upload.single('video'), (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: 'No video file uploaded' });
        }

        // Parse form data
        const { topic, category, theme, colors, tags } = req.body;

        // Create metadata object
        const metadata = {
            id: `video_${Date.now()}`,
            filename: req.file.filename,
            originalName: req.file.originalname,
            path: `/public/${req.file.filename}`,
            size: req.file.size,
            mimetype: req.file.mimetype,
            topic: topic,
            category: category,
            theme: theme,
            colors: JSON.parse(colors || '[]'),
            tags: JSON.parse(tags || '[]'),
            uploadedAt: new Date().toISOString(),
            searchableText: `${topic} ${category} ${theme} ${JSON.parse(colors || '[]').join(' ')} ${JSON.parse(tags || '[]').join(' ')}`
        };

        // Save metadata to JSON file
        const metadataDir = path.join(__dirname, '../metadata');
        if (!fs.existsSync(metadataDir)) {
            fs.mkdirSync(metadataDir, { recursive: true });
        }

        const metadataFilename = `${path.parse(req.file.filename).name}.json`;
        const metadataPath = path.join(metadataDir, metadataFilename);

        fs.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2));

        console.log('✅ Video uploaded successfully:', req.file.filename);
        console.log('✅ Metadata saved:', metadataFilename);

        res.json({
            success: true,
            message: 'Video uploaded successfully',
            videoPath: `/public/${req.file.filename}`,
            metadataPath: `/metadata/${metadataFilename}`,
            metadata: metadata
        });

    } catch (error) {
        console.error('Error uploading video:', error);
        res.status(500).json({ error: error.message });
    }
});

// Get all videos with metadata
app.get('/videos', (req, res) => {
    try {
        const metadataDir = path.join(__dirname, '../metadata');
        
        if (!fs.existsSync(metadataDir)) {
            return res.json({ videos: [] });
        }

        const files = fs.readdirSync(metadataDir);
        const videos = files
            .filter(file => file.endsWith('.json'))
            .map(file => {
                const content = fs.readFileSync(path.join(metadataDir, file), 'utf8');
                return JSON.parse(content);
            })
            .sort((a, b) => new Date(b.uploadedAt) - new Date(a.uploadedAt));

        res.json({ videos });
    } catch (error) {
        console.error('Error fetching videos:', error);
        res.status(500).json({ error: error.message });
    }
});

// Get single video metadata
app.get('/video/:id', (req, res) => {
    try {
        const metadataDir = path.join(__dirname, '../metadata');
        const files = fs.readdirSync(metadataDir);
        
        for (const file of files) {
            if (file.endsWith('.json')) {
                const content = fs.readFileSync(path.join(metadataDir, file), 'utf8');
                const metadata = JSON.parse(content);
                if (metadata.id === req.params.id) {
                    return res.json(metadata);
                }
            }
        }

        res.status(404).json({ error: 'Video not found' });
    } catch (error) {
        console.error('Error fetching video:', error);
        res.status(500).json({ error: error.message });
    }
});

// Delete video and its metadata
app.delete('/video/:id', (req, res) => {
    try {
        const metadataDir = path.join(__dirname, '../metadata');
        const publicDir = path.join(__dirname, '../public');
        const files = fs.readdirSync(metadataDir);
        
        for (const file of files) {
            if (file.endsWith('.json')) {
                const metadataPath = path.join(metadataDir, file);
                const content = fs.readFileSync(metadataPath, 'utf8');
                const metadata = JSON.parse(content);
                
                if (metadata.id === req.params.id) {
                    // Delete video file
                    const videoPath = path.join(publicDir, metadata.filename);
                    if (fs.existsSync(videoPath)) {
                        fs.unlinkSync(videoPath);
                    }
                    
                    // Delete metadata file
                    fs.unlinkSync(metadataPath);
                    
                    console.log('🗑️ Deleted video:', metadata.filename);
                    return res.json({ success: true, message: 'Video deleted successfully' });
                }
            }
        }

        res.status(404).json({ error: 'Video not found' });
    } catch (error) {
        console.error('Error deleting video:', error);
        res.status(500).json({ error: error.message });
    }
});

// Endpoint to get all metadata for Meilisearch sync
app.get('/meilisearch/update', (req, res) => {
    try {
        const metadataDir = path.join(__dirname, '../metadata');
        
        if (!fs.existsSync(metadataDir)) {
            return res.json({ documents: [] });
        }

        const files = fs.readdirSync(metadataDir);
        const documents = files
            .filter(file => file.endsWith('.json'))
            .map(file => {
                const content = fs.readFileSync(path.join(metadataDir, file), 'utf8');
                return JSON.parse(content);
            });

        res.json({ documents, count: documents.length });
    } catch (error) {
        console.error('Error preparing Meilisearch update:', error);
        res.status(500).json({ error: error.message });
    }
});

app.listen(PORT, () => {
    console.log(`🚀 Server is running on http://localhost:${PORT}`);
    console.log(`📁 Upload folder: ${path.join(__dirname, '../public')}`);
    console.log(`📄 Metadata folder: ${path.join(__dirname, '../metadata')}`);
});
