"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLogRouter = createLogRouter;
const express_1 = __importDefault(require("express"));
const zod_1 = require("zod");
const logRepository_js_1 = require("../../repositories/logRepository.js");
const createLog_js_1 = require("../../use-cases/createLog.js");
const createBulkLog_js_1 = require("../../use-cases/createBulkLog.js");
const getLogById_js_1 = require("../../use-cases/getLogById.js");
const getAllLogs_js_1 = require("../../use-cases/getAllLogs.js");
// Validation schemas
const LogMetadataSchema = zod_1.z.object({
    id: zod_1.z.string().optional(),
    logId: zod_1.z.string().optional(),
    key: zod_1.z.string(),
    value: zod_1.z.string().default("No value"),
});
const LogCreateSchema = zod_1.z.object({
    projectId: zod_1.z.string(),
    level: zod_1.z.string(),
    message: zod_1.z.string(),
    timestamp: zod_1.z.string(),
    metadata: zod_1.z.array(LogMetadataSchema).optional(),
});
const BulkLogCreateSchema = zod_1.z.object({
    logs: zod_1.z.array(LogCreateSchema),
});
const LogCursorSchema = zod_1.z.object({
    id: zod_1.z.string(),
    timestamp: zod_1.z.string(),
});
const LogPaginationParamsSchema = zod_1.z.object({
    limit: zod_1.z.string(),
    cursor: LogCursorSchema.optional(),
    sortDirection: zod_1.z.enum(['asc', 'desc']),
});
// Validation middleware
const validateBody = (schema) => {
    return (req, res, next) => {
        try {
            req.body = schema.parse(req.body);
            next();
        }
        catch (error) {
            if (error instanceof zod_1.z.ZodError) {
                res.status(400).json({ error: 'Validation error', details: error.errors });
                return;
            }
            next(error);
        }
    };
};
const validateParams = (schema) => {
    return (req, res, next) => {
        try {
            req.params = schema.parse(req.params);
            next();
        }
        catch (error) {
            if (error instanceof zod_1.z.ZodError) {
                res.status(400).json({ error: 'Validation error', details: error.errors });
                return;
            }
            next(error);
        }
    };
};
const validateQuery = (schema) => {
    return (req, res, next) => {
        try {
            const validatedQuery = schema.parse(req.query);
            req.validatedQuery = validatedQuery;
            next();
        }
        catch (error) {
            if (error instanceof zod_1.z.ZodError) {
                res.status(400).json({ error: 'Validation error', details: error.errors });
                return;
            }
            next(error);
        }
    };
};
// Error handling middleware
const asyncHandler = (fn) => {
    return (req, res, next) => {
        Promise.resolve(fn(req, res, next)).catch(next);
    };
};
function createLogRouter() {
    const router = express_1.default.Router();
    // Initialize repository and use cases
    const logRepository = new logRepository_js_1.LogRepository();
    const createLog = new createLog_js_1.CreateLog(logRepository);
    const createBulkLog = new createBulkLog_js_1.CreateBulkLog(logRepository);
    const getLogById = new getLogById_js_1.GetLogById(logRepository);
    const getAllLogs = new getAllLogs_js_1.GetAllLogs(logRepository);
    // POST /api/logs
    router.post('/', validateBody(LogCreateSchema), asyncHandler(async (req, res) => {
        const logData = req.body;
        const log = await createLog.execute({
            message: logData.message,
            projectId: logData.projectId,
            level: logData.level,
            timestamp: logData.timestamp,
            metadata: logData.metadata || []
        });
        res.status(201).json(log);
    }));
    // POST /api/logs/bulk
    router.post('/bulk', validateBody(BulkLogCreateSchema), asyncHandler(async (req, res) => {
        const { logs } = req.body;
        const logsData = logs.map((logData) => ({
            message: logData.message,
            projectId: logData.projectId,
            level: logData.level,
            timestamp: logData.timestamp,
            metadata: logData.metadata || []
        }));
        const createdLogs = await createBulkLog.execute(logsData);
        res.status(201).json(createdLogs);
    }));
    // GET /api/logs
    router.get('/', validateQuery(LogPaginationParamsSchema.partial()), asyncHandler(async (req, res) => {
        const params = req.validatedQuery || req.query;
        const logs = await getAllLogs.execute(params);
        res.json(logs);
    }));
    // GET /api/logs/:id
    router.get('/:id', validateParams(zod_1.z.object({ id: zod_1.z.string() })), asyncHandler(async (req, res) => {
        const { id } = req.params;
        const log = await getLogById.execute(id);
        if (!log) {
            res.status(404).json({ error: 'Log not found' });
            return;
        }
        res.json(log);
    }));
    return router;
}
//# sourceMappingURL=logRoutes.js.map