"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.logger = void 0;
exports.createModuleLogger = createModuleLogger;
const pino_1 = __importDefault(require("pino"));
const path_1 = require("path");
const fs_1 = require("fs");
const logDir = (0, path_1.resolve)(process.cwd(), 'data', 'logs');
(0, fs_1.mkdirSync)(logDir, { recursive: true });
// ── Log Rotation ──
// Max 10 MB per log file, keep 5 rotated files.
const MAX_LOG_BYTES = 10 * 1024 * 1024; // 10 MB
const MAX_ROTATED_FILES = 5;
function rotateIfNeeded(filePath) {
    try {
        if (!(0, fs_1.existsSync)(filePath))
            return;
        const stats = (0, fs_1.statSync)(filePath);
        if (stats.size < MAX_LOG_BYTES)
            return;
        // Shift existing rotated files: .4 -> .5 (delete), .3 -> .4, .2 -> .3, .1 -> .2
        for (let i = MAX_ROTATED_FILES; i >= 1; i--) {
            const src = `${filePath}.${i}`;
            if (!(0, fs_1.existsSync)(src))
                continue;
            if (i === MAX_ROTATED_FILES) {
                (0, fs_1.unlinkSync)(src);
            }
            else {
                (0, fs_1.renameSync)(src, `${filePath}.${i + 1}`);
            }
        }
        // Current -> .1
        (0, fs_1.renameSync)(filePath, `${filePath}.1`);
    }
    catch {
        // Rotation failure is non-fatal; log continues to current file.
    }
}
// Rotate on startup so large files from previous runs are archived immediately.
const appLogPath = (0, path_1.resolve)(logDir, 'app.log');
const errLogPath = (0, path_1.resolve)(logDir, 'errors.log');
rotateIfNeeded(appLogPath);
rotateIfNeeded(errLogPath);
const targets = [
    {
        target: 'pino/file',
        options: { destination: appLogPath, mkdir: true },
        level: 'info',
    },
    {
        target: 'pino/file',
        options: { destination: errLogPath, mkdir: true },
        level: 'error',
    },
];
if (process.env.NODE_ENV !== 'production') {
    targets.push({
        target: 'pino-pretty',
        options: { colorize: true },
        level: 'debug',
    });
}
const transport = pino_1.default.transport({ targets });
exports.logger = (0, pino_1.default)({ level: 'debug' }, transport);
function createModuleLogger(module) {
    return exports.logger.child({ module });
}
//# sourceMappingURL=logger.js.map