"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NotificationService = void 0;
const path_1 = require("path");
const config_js_1 = require("../../utils/config.js");
const file_ops_js_1 = require("../data-store/file-ops.js");
const logger_js_1 = require("../../utils/logger.js");
const log = (0, logger_js_1.createModuleLogger)('notification');
const MAX_STORED = 200;
class NotificationService {
    filePath;
    constructor(dataDir) {
        const base = dataDir ?? config_js_1.config.dataDir;
        this.filePath = (0, path_1.join)(base, 'notifications', 'notifications.json');
    }
    async init() {
        const dir = (0, path_1.join)(this.filePath, '..');
        await (0, file_ops_js_1.ensureDir)(dir);
    }
    async load() {
        const data = await (0, file_ops_js_1.readJSON)(this.filePath);
        return data ?? [];
    }
    async save(notifications) {
        await (0, file_ops_js_1.atomicWriteJSON)(this.filePath, notifications);
    }
    async create(input) {
        const notifications = await this.load();
        const notification = {
            ...input,
            id: crypto.randomUUID(),
            read: false,
            createdAt: new Date().toISOString(),
        };
        notifications.push(notification);
        // Trim to MAX_STORED, keeping newest
        const trimmed = notifications.length > MAX_STORED
            ? notifications
                .sort((a, b) => new Date(b.createdAt).getTime() -
                new Date(a.createdAt).getTime())
                .slice(0, MAX_STORED)
            : notifications;
        await this.save(trimmed);
        log.info({ id: notification.id, type: notification.type }, 'Notification created');
        return notification;
    }
    async list(options) {
        const limit = options?.limit ?? 50;
        const unreadOnly = options?.unreadOnly ?? false;
        let notifications = await this.load();
        if (unreadOnly) {
            notifications = notifications.filter((n) => !n.read);
        }
        return notifications
            .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
            .slice(0, limit);
    }
    async markAsRead(id) {
        const notifications = await this.load();
        const target = notifications.find((n) => n.id === id);
        if (!target) {
            log.warn({ id }, 'Notification not found for markAsRead');
            return;
        }
        target.read = true;
        await this.save(notifications);
    }
    async markAllAsRead() {
        const notifications = await this.load();
        for (const n of notifications) {
            n.read = true;
        }
        await this.save(notifications);
    }
    async getUnreadCount() {
        const notifications = await this.load();
        return notifications.filter((n) => !n.read).length;
    }
}
exports.NotificationService = NotificationService;
//# sourceMappingURL=index.js.map