import { MemorietArchives, Memoriets, Notes, Users } from "../../../models/index.js";
import deleteNote from "../../../services/note/delete.js";
import { queueLogger } from "../../logger.js";
import { genId } from "../../../misc/gen-id.js";
const logger = queueLogger.createSubLogger("check-expired-memoriets");
export async function checkExpiredMemoriets() {
    logger.info("Checking expired Memoriets...");
    const expired = await Memoriets.createQueryBuilder("memoriet").where("memoriet.expiresAt IS NOT NULL").andWhere("memoriet.expiresAt < :now", {
        now: new Date()
    }).getMany();
    for (const memoriet of expired){
        const note = await Notes.findOneBy({
            id: memoriet.noteId
        });
        if (note != null) {
            const user = await Users.findOneBy({
                id: note.userId
            });
            if (user != null) {
                await MemorietArchives.save({
                    id: genId(),
                    createdAt: memoriet.createdAt,
                    deletedAt: new Date(),
                    userId: memoriet.userId,
                    text: note.text?.replace(/\n?#Memoriet\b/gi, "").trim() || null,
                    cw: note.cw,
                    fileIds: note.fileIds,
                    textLayers: memoriet.textLayers,
                    visibility: note.visibility
                }).catch((err)=>{
                    logger.warn(`Failed to archive expired Memoriet ${memoriet.id}: ${err}`);
                });
                await deleteNote(user, note, true).catch((err)=>{
                    logger.warn(`Failed to delete expired Memoriet note ${note.id}: ${err}`);
                });
            }
        }
        await Memoriets.delete(memoriet.id);
    }
    logger.succ("All expired Memoriets checked.");
    return `done: ${expired.length}`;
}
