"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createUploadRoutes = createUploadRoutes;
const express_1 = require("express");
const multer_1 = __importDefault(require("multer"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
function createUploadRoutes(ctx) {
    const router = (0, express_1.Router)();
    const uploadDir = process.env.UPLOAD_DIR || path_1.default.join(process.cwd(), 'uploads');
    if (!fs_1.default.existsSync(uploadDir))
        fs_1.default.mkdirSync(uploadDir, { recursive: true });
    const storage = multer_1.default.diskStorage({
        destination: (_req, _file, cb) => cb(null, uploadDir),
        filename: (_req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`),
    });
    const upload = (0, multer_1.default)({ storage, limits: { fileSize: 5 * 1024 * 1024 } });
    // POST / — Upload file
    router.post('/', upload.single('file'), async (req, res) => {
        try {
            if (!req.file)
                return res.status(400).json({ error: 'Nenhum arquivo enviado' });
            const url = `/uploads/${req.file.filename}`;
            await ctx.hooks.emit('upload:completed', { filename: req.file.filename, url });
            res.json({ url, filename: req.file.filename, size: req.file.size });
        }
        catch (err) {
            res.status(500).json({ error: 'Erro no upload' });
        }
    });
    // POST /logo — Upload partner logo
    router.post('/logo', upload.single('logo'), async (req, res) => {
        try {
            if (!req.file)
                return res.status(400).json({ error: 'Nenhum logo enviado' });
            const url = `/uploads/${req.file.filename}`;
            res.json({ url, filename: req.file.filename });
        }
        catch (err) {
            res.status(500).json({ error: 'Erro no upload' });
        }
    });
    // DELETE /:filename — Delete file
    router.delete('/:filename', async (req, res) => {
        try {
            const filePath = path_1.default.join(uploadDir, req.params.filename);
            if (fs_1.default.existsSync(filePath)) {
                fs_1.default.unlinkSync(filePath);
                await ctx.hooks.emit('upload:deleted', { filename: req.params.filename });
                res.json({ message: 'Arquivo removido' });
            }
            else {
                res.status(404).json({ error: 'Arquivo não encontrado' });
            }
        }
        catch (err) {
            res.status(500).json({ error: 'Erro ao remover' });
        }
    });
    return router;
}
//# sourceMappingURL=routes.js.map