import { randomBytes } from "node:crypto";
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { StoredScheduleSchema } from "./types.js";
function generateScheduleId() {
    return randomBytes(4).toString("hex");
}
export class ScheduleStore {
    constructor(dir) {
        this.dir = dir;
    }
    filePath(id) {
        return join(this.dir, `${id}.json`);
    }
    async ensureDir() {
        await mkdir(this.dir, { recursive: true });
    }
    async list() {
        await this.ensureDir();
        const entries = await readdir(this.dir, { withFileTypes: true });
        const schedules = await Promise.all(entries
            .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
            .map(async (entry) => {
            const content = await readFile(join(this.dir, entry.name), "utf-8");
            return StoredScheduleSchema.parse(JSON.parse(content));
        }));
        return schedules.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
    }
    async get(id) {
        await this.ensureDir();
        try {
            const content = await readFile(this.filePath(id), "utf-8");
            return StoredScheduleSchema.parse(JSON.parse(content));
        }
        catch (error) {
            if (error.code === "ENOENT") {
                return null;
            }
            throw error;
        }
    }
    async create(schedule) {
        const created = { ...schedule, id: generateScheduleId() };
        await this.put(created);
        return created;
    }
    async put(schedule) {
        await this.ensureDir();
        await writeFile(this.filePath(schedule.id), JSON.stringify(schedule, null, 2), "utf-8");
    }
    async delete(id) {
        await this.ensureDir();
        await rm(this.filePath(id), { force: true });
    }
}
//# sourceMappingURL=store.js.map