import define from "../../../define.js";
import { ApiError } from "../../../error.js";
import { Notes, PromoNotes } from "../../../../../models/index.js";
export const meta = {
    tags: [
        "admin"
    ],
    requireCredential: true,
    requireModerator: true,
    errors: {
        noSuchNote: {
            message: "No such note.",
            code: "NO_SUCH_NOTE",
            id: "ee449fbe-af2a-453b-9cae-cf2fe7c895fc"
        },
        alreadyPromoted: {
            message: "The note has already promoted.",
            code: "ALREADY_PROMOTED",
            id: "ae427aa2-7a41-484f-a18c-2c1104051604"
        },
        notAdService: {
            message: "The note must have #AdService.",
            code: "NOT_AD_SERVICE",
            id: "970a4d57-7b67-4540-80ea-f210041724ef"
        }
    }
};
export const paramDef = {
    type: "object",
    properties: {
        noteId: {
            type: "string",
            format: "misskey:id"
        },
        expiresAt: {
            type: "integer"
        },
        credits: {
            type: "integer",
            minimum: 1,
            maximum: 100000,
            default: 1
        }
    },
    required: [
        "noteId"
    ]
};
export default define(meta, paramDef, async (ps, user)=>{
    const note = await Notes.findOneBy({
        id: ps.noteId
    });
    if (note == null) {
        throw new ApiError(meta.errors.noSuchNote);
    }
    if (!note.tags.includes("adservice")) {
        throw new ApiError(meta.errors.notAdService);
    }
    const expiresAt = ps.expiresAt ? new Date(ps.expiresAt) : new Date(Date.now() + 30 * 86400000);
    const credits = ps.credits ?? 1;
    const exist = await PromoNotes.findOneBy({
        noteId: note.id
    });
    if (exist) {
        await PromoNotes.update(note.id, {
            expiresAt: exist.expiresAt.getTime() > expiresAt.getTime() ? exist.expiresAt : expiresAt,
            totalCredits: exist.totalCredits + credits,
            remainingCredits: exist.remainingCredits + credits
        });
        return;
    }
    await PromoNotes.insert({
        noteId: note.id,
        expiresAt,
        totalCredits: credits,
        remainingCredits: credits,
        userId: note.userId
    });
});
