import { Memoriets, MemorietViews, Users } from "../../../../models/index.js";
import define from "../../define.js";
import { ApiError } from "../../error.js";
export const meta = {
    tags: [
        "memoriet"
    ],
    requireCredential: true,
    kind: "read:account",
    res: {
        type: "array",
        optional: false,
        nullable: false,
        items: {
            type: "object",
            optional: false,
            nullable: false,
            properties: {
                viewedAt: {
                    type: "string",
                    optional: false,
                    nullable: false
                },
                user: {
                    type: "object",
                    optional: false,
                    nullable: false,
                    ref: "User"
                }
            }
        }
    },
    errors: {
        noSuchMemoriet: {
            message: "No such Memoriet.",
            code: "NO_SUCH_MEMORIET",
            id: "1470626e-d318-4e01-9294-fbfa1260e6c4",
            httpStatusCode: 404
        },
        accessDenied: {
            message: "You cannot see viewers of this Memoriet.",
            code: "ACCESS_DENIED",
            id: "d705b05b-23c0-4b93-a5bb-2c303c66db2b",
            httpStatusCode: 403
        }
    }
};
export const paramDef = {
    type: "object",
    properties: {
        memorietId: {
            type: "string",
            format: "misskey:id"
        },
        limit: {
            type: "integer",
            minimum: 1,
            maximum: 100,
            default: 50
        },
        offset: {
            type: "integer",
            minimum: 0,
            default: 0
        }
    },
    required: [
        "memorietId"
    ]
};
export default define(meta, paramDef, async (ps, user)=>{
    const memoriet = await Memoriets.findOneBy({
        id: ps.memorietId
    });
    if (!memoriet) throw new ApiError(meta.errors.noSuchMemoriet);
    if (memoriet.userId !== user.id) throw new ApiError(meta.errors.accessDenied);
    const views = await MemorietViews.find({
        where: {
            memorietId: memoriet.id
        },
        order: {
            viewedAt: "DESC"
        },
        skip: ps.offset,
        take: ps.limit
    });
    const users = await Users.packMany(views.map((view)=>view.viewerId), user, {
        detail: false
    });
    return views.map((view, index)=>({
            viewedAt: view.viewedAt.toISOString(),
            user: users[index]
        }));
});
