"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 joi_1 = __importDefault(require("joi"));
const router = (0, express_1.Router)();
function normalizeDate(dateInput) {
    if (typeof dateInput === 'string') {
        const [year, month, day] = dateInput.split('-');
        return new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
    }
    if (dateInput instanceof Date) {
        const year = dateInput.getFullYear();
        const month = dateInput.getMonth();
        const day = dateInput.getDate();
        return new Date(year, month, day);
    }
    return dateInput;
}
const createDocketEntrySchema = joi_1.default.object({
    date: joi_1.default.date().required(),
    title: joi_1.default.string().required().max(500),
    summary: joi_1.default.string().required(),
    notes: joi_1.default.string().optional().allow(''),
});
const updateDocketEntrySchema = joi_1.default.object({
    date: joi_1.default.date().optional(),
    title: joi_1.default.string().optional().max(500),
    summary: joi_1.default.string().optional(),
    notes: joi_1.default.string().optional().allow(''),
});
router.get('/', (0, errorHandler_1.asyncHandler)(async (req, res) => {
    const entries = await index_1.prisma.docketEntry.findMany({
        include: {
            documents: {
                orderBy: {
                    displayOrder: 'asc',
                },
            },
        },
        orderBy: {
            date: 'asc',
        },
    });
    res.json({
        success: true,
        entries,
    });
}));
router.get('/:id', auth_1.authenticateToken, (0, errorHandler_1.asyncHandler)(async (req, res) => {
    const entryId = parseInt(req.params.id);
    if (isNaN(entryId)) {
        return res.status(400).json({
            success: false,
            message: 'Invalid entry ID',
        });
    }
    const entry = await index_1.prisma.docketEntry.findUnique({
        where: { id: entryId },
        include: {
            documents: {
                orderBy: {
                    displayOrder: 'asc',
                },
            },
        },
    });
    if (!entry) {
        return res.status(404).json({
            success: false,
            message: 'Docket entry not found',
        });
    }
    res.json({
        success: true,
        entry,
    });
}));
router.post('/', auth_1.authenticateToken, (0, errorHandler_1.asyncHandler)(async (req, res) => {
    const { error, value } = createDocketEntrySchema.validate(req.body);
    if (error) {
        return res.status(400).json({
            success: false,
            message: error.details[0].message,
        });
    }
    const normalizedData = { ...value };
    if (value.date) {
        normalizedData.date = normalizeDate(value.date);
    }
    const entry = await index_1.prisma.docketEntry.create({
        data: normalizedData,
        include: {
            documents: {
                orderBy: {
                    displayOrder: 'asc',
                },
            },
        },
    });
    res.status(201).json({
        success: true,
        message: 'Docket entry created successfully',
        entry,
    });
}));
router.put('/:id', auth_1.authenticateToken, (0, errorHandler_1.asyncHandler)(async (req, res) => {
    const entryId = parseInt(req.params.id);
    if (isNaN(entryId)) {
        return res.status(400).json({
            success: false,
            message: 'Invalid entry ID',
        });
    }
    const { error, value } = updateDocketEntrySchema.validate(req.body);
    if (error) {
        return res.status(400).json({
            success: false,
            message: error.details[0].message,
        });
    }
    const normalizedData = { ...value };
    if (value.date) {
        normalizedData.date = normalizeDate(value.date);
    }
    try {
        const entry = await index_1.prisma.docketEntry.update({
            where: { id: entryId },
            data: normalizedData,
            include: {
                documents: {
                    orderBy: {
                        displayOrder: 'asc',
                    },
                },
            },
        });
        res.json({
            success: true,
            message: 'Docket entry updated successfully',
            entry,
        });
    }
    catch (error) {
        if (error.code === 'P2025') {
            return res.status(404).json({
                success: false,
                message: 'Docket entry not found',
            });
        }
        throw error;
    }
}));
router.delete('/:id', auth_1.authenticateToken, (0, errorHandler_1.asyncHandler)(async (req, res) => {
    const entryId = parseInt(req.params.id);
    if (isNaN(entryId)) {
        return res.status(400).json({
            success: false,
            message: 'Invalid entry ID',
        });
    }
    try {
        await index_1.prisma.document.deleteMany({
            where: { docketEntryId: entryId },
        });
        await index_1.prisma.docketEntry.delete({
            where: { id: entryId },
        });
        res.json({
            success: true,
            message: 'Docket entry deleted successfully',
        });
    }
    catch (error) {
        if (error.code === 'P2025') {
            return res.status(404).json({
                success: false,
                message: 'Docket entry not found',
            });
        }
        throw error;
    }
}));
exports.default = router;
//# sourceMappingURL=docket.js.map