"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const multer_1 = __importDefault(require("multer"));
const DIContainer_1 = require("../../Application/Services/DIContainer");
const AuthMiddleware_1 = require("../../Application/Services/AuthMiddleware");
const Logger_1 = require("../../Application/Services/Logger");
const router = express_1.default.Router();
const container = DIContainer_1.DIContainer.getInstance();
// Configure multer for file uploads
const upload = (0, multer_1.default)({
    storage: multer_1.default.memoryStorage(),
    limits: {
        fileSize: 10 * 1024 * 1024, // 10MB limit
    },
    fileFilter: (req, file, cb) => {
        if (file.mimetype === 'application/json' || file.originalname.endsWith('.spr')) {
            cb(null, true);
        }
        else {
            cb(new Error('Only JSON and .spr files are allowed'));
        }
    }
});
// Export deck to .spr file (encrypted) - users can only export their own decks
router.get('/export/:deckId', AuthMiddleware_1.authRequired, async (req, res) => {
    try {
        const { deckId } = req.params;
        const userId = req.user.userId;
        (0, Logger_1.logRequest)('Export deck endpoint accessed', req, res, { deckId, userId });
        // Check if user owns the deck
        const deck = await container.deckRepository.findById(deckId);
        if (!deck) {
            (0, Logger_1.logWarning)('Deck not found for export', { deckId, userId }, req, res);
            return res.status(404).json({ error: 'Deck not found' });
        }
        // Users can only export their own decks
        if (deck.userid !== userId) {
            (0, Logger_1.logWarning)('Access denied - user attempted to export deck they do not own', {
                deckId,
                userId,
                deckOwnerId: deck.userid
            }, req, res);
            return res.status(403).json({ error: 'Access denied - you can only export your own decks' });
        }
        const sprData = await container.deckImportExportService.exportDeckToSpr(deckId, userId);
        res.setHeader('Content-Type', 'application/octet-stream');
        res.setHeader('Content-Disposition', `attachment; filename="${deck.name || 'deck'}.spr"`);
        (0, Logger_1.logRequest)('Deck exported successfully', req, res, {
            deckId,
            userId,
            deckName: deck.name,
            fileSize: sprData.length
        });
        res.send(sprData);
    }
    catch (error) {
        (0, Logger_1.logError)('Export deck endpoint error', error, req, res);
        res.status(500).json({ error: 'Internal server error' });
    }
});
// Import deck from .spr file (encrypted) - imported deck will be owned by the importing user
router.post('/import', AuthMiddleware_1.authRequired, upload.single('file'), async (req, res) => {
    try {
        const userId = req.user.userId;
        (0, Logger_1.logRequest)('Import deck endpoint accessed', req, res, {
            userId,
            hasFile: !!req.file,
            fileName: req.file?.originalname,
            fileSize: req.file?.size
        });
        if (!req.file) {
            (0, Logger_1.logWarning)('No file uploaded for deck import', { userId }, req, res);
            return res.status(400).json({ error: 'No file uploaded' });
        }
        const fileBuffer = req.file.buffer;
        // Import the deck and assign ownership to the current user
        const result = await container.deckImportExportService.importDeckFromSpr(fileBuffer, userId);
        (0, Logger_1.logRequest)('Deck imported successfully', req, res, {
            userId,
            deckId: result.id,
            deckName: result.name || 'Unknown',
            fileName: req.file.originalname,
            fileSize: req.file.size
        });
        res.json({
            success: true,
            message: 'Deck imported successfully and added to your collection',
            deckId: result.id
        });
    }
    catch (error) {
        (0, Logger_1.logError)('Import deck endpoint error', error, req, res);
        if (error instanceof Error && error.message.includes('Invalid')) {
            return res.status(400).json({ error: 'Invalid file format or corrupted data' });
        }
        else {
            res.status(500).json({ error: 'Internal server error' });
        }
    }
});
exports.default = router;
//# sourceMappingURL=deckImportExportRouter.js.map