import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
export class SubDiscussionStore {
    filePath;
    byChannelId = new Map();
    constructor(filePath) {
        this.filePath = filePath;
        this.load();
    }
    load() {
        if (!existsSync(this.filePath))
            return;
        try {
            const data = JSON.parse(readFileSync(this.filePath, 'utf8'));
            for (const e of data.entries ?? []) {
                if (e?.subChannelId)
                    this.byChannelId.set(e.subChannelId, e);
            }
        }
        catch {
            // Corrupt file → start empty; first mutation rewrites cleanly.
        }
    }
    persist() {
        mkdirSync(dirname(this.filePath), { recursive: true });
        const data = { entries: [...this.byChannelId.values()] };
        writeFileSync(this.filePath, JSON.stringify(data, null, 2));
    }
    list() {
        return [...this.byChannelId.values()];
    }
    find(subChannelId) {
        return this.byChannelId.get(subChannelId);
    }
    add(entry) {
        this.byChannelId.set(entry.subChannelId, entry);
        this.persist();
    }
    remove(subChannelId) {
        const e = this.byChannelId.get(subChannelId);
        if (!e)
            return undefined;
        this.byChannelId.delete(subChannelId);
        this.persist();
        return e;
    }
}
