"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 = require("express");
const index_1 = require("../index");
const errorHandler_1 = require("../middleware/errorHandler");
const auth_1 = require("../middleware/auth");
const multer_1 = __importDefault(require("multer"));
const uuid_1 = require("uuid");
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const joi_1 = __importDefault(require("joi"));
const router = (0, express_1.Router)();
const storage = multer_1.default.diskStorage({
    destination: (req, file, cb) => {
        const uploadDir = process.env['UPLOAD_DIR'] || './uploads';
        if (!fs_1.default.existsSync(uploadDir)) {
            fs_1.default.mkdirSync(uploadDir, { recursive: true });
        }
        cb(null, uploadDir);
    },
    filename: (req, file, cb) => {
        const uuid = (0, uuid_1.v4)();
        const extension = path_1.default.extname(file.originalname);
        cb(null, `${uuid}${extension}`);
    },
});
const upload = (0, multer_1.default)({
    storage,
    limits: {
        fileSize: parseInt(process.env['MAX_FILE_SIZE'] || '262144000'),
    },
    fileFilter: (req, file, cb) => {
        const allowedMimeTypes = [
            'application/pdf',
            'application/x-pdf',
            'application/acrobat',
            'applications/vnd.pdf',
            'text/pdf',
            'text/x-pdf'
        ];
        const isValidPDF = allowedMimeTypes.includes(file.mimetype) ||
            file.originalname.toLowerCase().endsWith('.pdf');
        console.log('Upload attempt:', {
            mimetype: file.mimetype,
            filename: file.originalname,
            isValid: isValidPDF
        });
        if (isValidPDF) {
            cb(null, true);
        }
        else {
            cb(new Error(`Only PDF files are allowed. Received: ${file.mimetype} for file: ${file.originalname}`));
        }
    },
});
const createDocumentSchema = joi_1.default.object({
    docketEntryId: joi_1.default.number().integer().required(),
    title: joi_1.default.string().required().max(500),
    summary: joi_1.default.string().optional().allow(''),
    notes: joi_1.default.string().optional().allow(''),
    displayOrder: joi_1.default.number().integer().min(0).optional(),
});
const updateDocumentSchema = joi_1.default.object({
    title: joi_1.default.string().optional().max(500),
    summary: joi_1.default.string().optional().allow(''),
    notes: joi_1.default.string().optional().allow(''),
    displayOrder: joi_1.default.number().integer().min(0).optional(),
});
router.get('/:id/download', (0, errorHandler_1.asyncHandler)(async (req, res) => {
    const documentId = parseInt(req.params['id'] || '');
    if (isNaN(documentId)) {
        return res.status(400).json({
            success: false,
            message: 'Invalid document ID',
        });
    }
    const document = await index_1.prisma.document.findUnique({
        where: { id: documentId },
    });
    if (!document) {
        return res.status(404).json({
            success: false,
            message: 'Document not found',
        });
    }
    const filePath = document.filePath;
    if (!fs_1.default.existsSync(filePath)) {
        return res.status(404).json({
            success: false,
            message: 'File not found on server',
        });
    }
    res.setHeader('Content-Type', document.mimeType);
    res.setHeader('Content-Disposition', `inline; filename="${document.originalFilename}"`);
    const fileStream = fs_1.default.createReadStream(filePath);
    fileStream.pipe(res);
}));
router.post('/upload', auth_1.authenticateToken, upload.single('file'), (0, errorHandler_1.asyncHandler)(async (req, res) => {
    if (!req.file) {
        return res.status(400).json({
            success: false,
            message: 'No file uploaded',
        });
    }
    const { error, value } = createDocumentSchema.validate(req.body);
    if (error) {
        fs_1.default.unlinkSync(req.file.path);
        return res.status(400).json({
            success: false,
            message: error.details[0].message,
        });
    }
    const { docketEntryId, title, summary, notes, displayOrder } = value;
    const docketEntry = await index_1.prisma.docketEntry.findUnique({
        where: { id: docketEntryId },
    });
    if (!docketEntry) {
        fs_1.default.unlinkSync(req.file.path);
        return res.status(404).json({
            success: false,
            message: 'Docket entry not found',
        });
    }
    let finalDisplayOrder = displayOrder;
    if (finalDisplayOrder === undefined) {
        const lastDocument = await index_1.prisma.document.findFirst({
            where: { docketEntryId },
            orderBy: { displayOrder: 'desc' },
        });
        finalDisplayOrder = lastDocument ? lastDocument.displayOrder + 1 : 0;
    }
    const document = await index_1.prisma.document.create({
        data: {
            docketEntryId,
            title,
            originalFilename: req.file.originalname,
            storedFilename: req.file.filename,
            filePath: req.file.path,
            fileSize: req.file.size,
            mimeType: req.file.mimetype,
            summary: summary || '',
            notes: notes || '',
            displayOrder: finalDisplayOrder,
        },
    });
    res.status(201).json({
        success: true,
        message: 'Document uploaded successfully',
        document,
    });
}));
router.put('/:id', auth_1.authenticateToken, (0, errorHandler_1.asyncHandler)(async (req, res) => {
    const documentId = parseInt(req.params['id'] || '');
    if (isNaN(documentId)) {
        return res.status(400).json({
            success: false,
            message: 'Invalid document ID',
        });
    }
    const { error, value } = updateDocumentSchema.validate(req.body);
    if (error) {
        return res.status(400).json({
            success: false,
            message: error.details[0].message,
        });
    }
    try {
        const document = await index_1.prisma.document.update({
            where: { id: documentId },
            data: value,
        });
        res.json({
            success: true,
            message: 'Document updated successfully',
            document,
        });
    }
    catch (error) {
        if (error.code === 'P2025') {
            return res.status(404).json({
                success: false,
                message: 'Document not found',
            });
        }
        throw error;
    }
}));
router.delete('/:id', auth_1.authenticateToken, (0, errorHandler_1.asyncHandler)(async (req, res) => {
    const documentId = parseInt(req.params['id'] || '');
    if (isNaN(documentId)) {
        return res.status(400).json({
            success: false,
            message: 'Invalid document ID',
        });
    }
    try {
        const document = await index_1.prisma.document.findUnique({
            where: { id: documentId },
        });
        if (!document) {
            return res.status(404).json({
                success: false,
                message: 'Document not found',
            });
        }
        if (fs_1.default.existsSync(document.filePath)) {
            fs_1.default.unlinkSync(document.filePath);
        }
        await index_1.prisma.document.delete({
            where: { id: documentId },
        });
        res.json({
            success: true,
            message: 'Document deleted successfully',
        });
    }
    catch (error) {
        if (error.code === 'P2025') {
            return res.status(404).json({
                success: false,
                message: 'Document not found',
            });
        }
        throw error;
    }
}));
exports.default = router;
//# sourceMappingURL=documents.js.map