#!/bin/bash

echo "🔧 Upload Dosya Kaybolma Sorunu - Hızlı Fix"
echo "==========================================="

cd /var/www/redone.vision/backend

# 1. Upload klasörlerini force oluştur
echo "1️⃣ Upload klasörleri force oluşturuluyor..."
mkdir -p /var/www/redone.vision/uploads/{temp,Movies/{Video/{Teaser,Riyad,Content},Poster/{Riyad,Content}},Series/{Video/{Teaser,Riyad,Content},Poster/{Riyad,Content}},Lifestyle/{Video/{Teaser,Content},Poster/Content},RedPulse/{Video/{Teaser,Content},Poster/Content}}

# 2. İzinleri agresif şekilde düzelt
echo "2️⃣ İzinler agresif şekilde düzeltiliyor..."
sudo chown -R www-data:www-data /var/www/redone.vision/uploads/
sudo chmod -R 777 /var/www/redone.vision/uploads/  # Geçici olarak full access

# 3. Upload.js'te debug ekle - Multer destination debug
echo "3️⃣ Upload.js debug ekleniyor..."
cp routes/upload.js routes/upload.js.backup.debug.$(date +%Y%m%d_%H%M%S)

# Add extensive logging to multer destination
cat > routes/upload.js << 'EOF'
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const router = express.Router();

// Simple auth
const verifyToken = (req, res, next) => {
    try {
        const authHeader = req.headers.authorization;
        if (authHeader && authHeader.startsWith('Bearer ')) {
            req.admin = { username: 'admin', role: 'admin' };
            console.log('🔐 Auth: Admin authenticated');
        }
        next();
    } catch (error) {
        console.log('⚠️ Auth warning:', error.message);
        next();
    }
};

// Generate content ID
function generateContentId(title, category) {
    const sanitizedTitle = (title || 'untitled')
        .toLowerCase()
        .replace(/[^a-z0-9]/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '');
    const timestamp = Date.now().toString().slice(-6);
    return `${category.toLowerCase()}-${sanitizedTitle}-${timestamp}`;
}

// Multer storage with EXTENSIVE DEBUG LOGGING
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        console.log('🔍 MULTER DESTINATION DEBUG:');
        console.log('   📋 req.body:', req.body);
        console.log('   📄 file.mimetype:', file.mimetype);
        
        const { category, subtype } = req.body;
        const isVideo = file.mimetype.startsWith("video/");
        const baseType = isVideo ? "Video" : "Poster";
        
        console.log('   🎯 category:', category);
        console.log('   🎯 subtype:', subtype);
        console.log('   🎯 isVideo:', isVideo);
        console.log('   🎯 baseType:', baseType);
        
        let uploadPath;
        
        if (!category || !subtype) {
            uploadPath = '/var/www/redone.vision/uploads/temp';
            console.log('   ⚠️ Missing category/subtype, using temp path');
        } else {
            uploadPath = `/var/www/redone.vision/uploads/${category}/${baseType}`;
            
            if (subtype === "Teaser") {
                uploadPath += "/Teaser";
            } else if (subtype === "Riyad") {
                uploadPath += "/Riyad";
            } else {
                uploadPath += "/Content";
            }
        }
        
        console.log('   📁 FINAL uploadPath:', uploadPath);
        
        try {
            // Check if path exists
            if (fs.existsSync(uploadPath)) {
                console.log('   ✅ Path exists');
            } else {
                console.log('   📁 Creating path...');
                fs.mkdirSync(uploadPath, { recursive: true });
                console.log('   ✅ Path created');
            }
            
            // Check permissions
            try {
                fs.accessSync(uploadPath, fs.constants.W_OK);
                console.log('   ✅ Path writable');
            } catch (permError) {
                console.log('   ❌ Path not writable:', permError.message);
            }
            
            cb(null, uploadPath);
            console.log('   🎯 Multer destination SUCCESS:', uploadPath);
            
        } catch (error) {
            console.error('   ❌ MULTER DESTINATION ERROR:', error);
            cb(error);
        }
    },
    filename: (req, file, cb) => {
        console.log('🔍 MULTER FILENAME DEBUG:');
        
        const { title } = req.body;
        const timestamp = Date.now();
        const ext = path.extname(file.originalname);
        
        let filename;
        if (title) {
            const cleanTitle = title.replace(/[^a-z0-9]/gi, '-').toLowerCase();
            filename = `${cleanTitle}-${timestamp}${ext}`;
        } else {
            filename = `upload-${timestamp}${ext}`;
        }
        
        console.log('   📄 Original filename:', file.originalname);
        console.log('   📄 Generated filename:', filename);
        console.log('   📄 Extension:', ext);
        
        cb(null, filename);
        console.log('   🎯 Multer filename SUCCESS:', filename);
    }
});

const upload = multer({
    storage: storage,
    limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10GB
    fileFilter: (req, file, cb) => {
        console.log('🔍 MULTER FILEFILTER DEBUG:');
        console.log('   📄 file.mimetype:', file.mimetype);
        console.log('   📄 file.originalname:', file.originalname);
        
        const allowedTypes = /jpeg|jpg|png|gif|webp|svg|mp4|webm|ogg|avi|mov|wmv|flv|mkv/;
        const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
        const mimetype = allowedTypes.test(file.mimetype);
        
        console.log('   ✅ extname check:', extname);
        console.log('   ✅ mimetype check:', mimetype);
        
        if (extname && mimetype) {
            console.log('   🎯 File filter PASS');
            return cb(null, true);
        } else {
            console.log('   ❌ File filter REJECT');
            cb(new Error('Sadece video ve görüntü dosyaları yüklenebilir!'));
        }
    }
});

// Upload endpoint with EXTENSIVE DEBUG
router.post('/file', verifyToken, upload.single('file'), async (req, res) => {
    console.log('🚀 UPLOAD REQUEST START');
    console.log('======================================');
    console.log('📤 Request timestamp:', new Date().toISOString());
    console.log('📋 Request body:', req.body);
    console.log('📄 File info:', req.file ? {
        filename: req.file.filename,
        originalname: req.file.originalname,
        mimetype: req.file.mimetype,
        size: req.file.size,
        destination: req.file.destination,
        path: req.file.path
    } : 'NO FILE');
    
    try {
        if (!req.file) {
            console.log('❌ No file in request');
            return res.status(400).json({
                success: false,
                message: 'Dosya yüklenmedi'
            });
        }

        const { title, category, subtype } = req.body;
        const isVideo = req.file.mimetype.startsWith('video/');
        
        // Check if file actually exists on disk
        const fileExists = fs.existsSync(req.file.path);
        console.log('📁 File exists on disk:', fileExists);
        
        if (fileExists) {
            const stats = fs.statSync(req.file.path);
            console.log('📊 File stats:', {
                size: stats.size,
                created: stats.birthtime,
                modified: stats.mtime
            });
        }
        
        let fileType;
        if (subtype === 'Teaser') {
            fileType = 'teaser';
        } else if (isVideo) {
            fileType = 'content';
        } else {
            fileType = 'poster';
        }
        
        const finalContentId = generateContentId(title, category);
        
        const responseData = {
            success: true,
            message: 'Dosya başarıyla yüklendi',
            data: {
                contentId: finalContentId,
                fileType: fileType,
                filename: req.file.filename,
                originalName: req.file.originalname,
                size: req.file.size,
                uploadPath: req.file.path,
                destination: req.file.destination,
                fileExists: fileExists,
                category: category,
                subtype: subtype,
                uploadedAt: new Date().toISOString()
            }
        };
        
        console.log('✅ UPLOAD SUCCESS RESPONSE:', responseData);
        res.json(responseData);
        
        console.log('🎯 UPLOAD REQUEST END - SUCCESS');
        console.log('======================================');
        
    } catch (error) {
        console.error('❌ UPLOAD ERROR:', error);
        console.log('🎯 UPLOAD REQUEST END - ERROR');
        console.log('======================================');
        
        res.status(500).json({
            success: false,
            message: 'Dosya yükleme hatası: ' + error.message,
            error: error.toString()
        });
    }
});

// Status endpoint
router.get('/status', (req, res) => {
    res.json({
        success: true,
        message: 'Upload service - DEBUG MODE',
        data: {
            service: 'Active with extensive logging',
            uploadPath: '/var/www/redone.vision/uploads/',
            timestamp: new Date().toISOString()
        }
    });
});

// Test file creation endpoint
router.post('/test-file', (req, res) => {
    try {
        const testPath = '/var/www/redone.vision/uploads/test-file.txt';
        fs.writeFileSync(testPath, `Test file created at ${new Date().toISOString()}`);
        
        const exists = fs.existsSync(testPath);
        
        res.json({
            success: true,
            message: 'Test file created',
            data: {
                path: testPath,
                exists: exists,
                timestamp: new Date().toISOString()
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Test file creation failed',
            error: error.message
        });
    }
});

module.exports = router;
EOF

# 4. Restart backend
echo "4️⃣ Backend restart (debug mode)..."
pm2 restart redone-backend
sleep 3

# 5. Test file creation
echo "5️⃣ Test file creation..."
test_response=$(curl -s -X POST https://redone.vision/api/upload/test-file)
echo "Test file response: $test_response"

# 6. Check if test file exists
if [ -f "/var/www/redone.vision/uploads/test-file.txt" ]; then
    echo "✅ Test file created successfully"
    ls -la /var/www/redone.vision/uploads/test-file.txt
else
    echo "❌ Test file creation failed"
fi

echo ""
echo "🎯 DEBUG MODE ACTIVATED!"
echo "======================="
echo "✅ Upload extensive logging enabled"
echo "✅ Permissions fixed (777 temporary)"
echo "✅ Test file endpoint added"
echo ""
echo "📋 Next steps:"
echo "1. Admin panel'de upload test yapın"
echo "2. PM2 logs'ta detaylı debug output'u izleyin:"
echo "   pm2 logs redone-backend --lines 0 -f"
echo ""
echo "🔍 Debug komutları:"
echo "   curl -X POST https://redone.vision/api/upload/test-file"
echo "   ls -la /var/www/redone.vision/uploads/"
echo "   pm2 logs redone-backend | grep -E '🔍|📁|✅|❌'"
echo ""
echo "🎬 Admin panel test:"
echo "   https://redone.vision/admin.html"
