import { genId } from "../../misc/gen-id.js";
import { ScheduledNotes, Users } from "../../models/index.js";
import { createNoteFromApiData } from "./create-from-api.js";
export async function scheduleNote(user, data, scheduledAt) {
    return await ScheduledNotes.save({
        id: genId(),
        createdAt: new Date(),
        scheduledAt,
        userId: user.id,
        status: "scheduled",
        data,
        noteId: null,
        error: null
    });
}
export async function publishScheduledNote(scheduledNoteId) {
    const scheduled = await ScheduledNotes.findOneBy({
        id: scheduledNoteId
    });
    if (!scheduled) return "skip: scheduled note not found";
    if (scheduled.status !== "scheduled") return `skip: status=${scheduled.status}`;
    if (scheduled.scheduledAt.getTime() > Date.now() + 1000) return "skip: not due yet";
    await ScheduledNotes.update(scheduled.id, {
        status: "processing",
        error: null
    });
    try {
        const user = await Users.findOneByOrFail({
            id: scheduled.userId
        });
        const note = await createNoteFromApiData(user, scheduled.data, scheduled.scheduledAt);
        await ScheduledNotes.update(scheduled.id, {
            status: "published",
            noteId: note.id,
            error: null
        });
        return `published: ${note.id}`;
    } catch (err) {
        await ScheduledNotes.update(scheduled.id, {
            status: "failed",
            error: err?.message ?? String(err)
        });
        throw err;
    }
}
