import rndstr from "rndstr";
import { Notes, PromoNotes } from "../../../../../models/index.js";
import define from "../../../define.js";
import { makePaginationQuery } from "../../../common/make-pagination-query.js";
export const meta = {
    tags: [
        "admin"
    ],
    requireCredential: true,
    requireModerator: true
};
export const paramDef = {
    type: "object",
    properties: {
        limit: {
            type: "integer",
            minimum: 1,
            maximum: 100,
            default: 10
        },
        sinceId: {
            type: "string",
            format: "misskey:id"
        },
        untilId: {
            type: "string",
            format: "misskey:id"
        }
    },
    required: []
};
export default define(meta, paramDef, async (ps, user)=>{
    const query = makePaginationQuery(Notes.createQueryBuilder("note"), ps.sinceId, ps.untilId).andWhere(`'adservice' = ANY(note.tags)`).innerJoinAndSelect("note.user", "user").leftJoinAndSelect("note.reply", "reply").leftJoinAndSelect("note.renote", "renote").leftJoinAndSelect("reply.user", "replyUser").leftJoinAndSelect("renote.user", "renoteUser");
    const notes = await query.take(ps.limit).getMany();
    if (notes.length === 0) return [];
    const promos = await PromoNotes.findBy(notes.map((note)=>({
            noteId: note.id
        })));
    return Promise.all(notes.map(async (note)=>{
        const promo = promos.find((item)=>item.noteId === note.id);
        const expiredCredits = promo && promo.expiresAt.getTime() <= Date.now() ? promo.remainingCredits : 0;
        note._prId_ = rndstr("a-z0-9", 8);
        return {
            id: note.id,
            note: await Notes.pack(note, user),
            expiresAt: promo?.expiresAt.toISOString() ?? null,
            totalCredits: promo?.totalCredits ?? 0,
            remainingCredits: promo?.remainingCredits ?? 0,
            expiredCredits
        };
    }));
});
