import { NoteFavorites } from "../../../../../models/index.js";
import define from "../../../define.js";
import { ApiError } from "../../../error.js";
import { getNote } from "../../../common/getters.js";
import { getGroupActor } from "../../../common/get-group-actor.js";
export const meta = {
    tags: [
        "notes",
        "favorites"
    ],
    requireCredential: true,
    kind: "write:favorites",
    errors: {
        noSuchNote: {
            message: "No such note.",
            code: "NO_SUCH_NOTE",
            id: "80848a2c-398f-4343-baa9-df1d57696c56"
        },
        notFavorited: {
            message: "You have not marked that note a favorite.",
            code: "NOT_FAVORITED",
            id: "b625fc69-635e-45e9-86f4-dbefbef35af5"
        },
        noSuchGroup: {
            message: "No such group.",
            code: "NO_SUCH_GROUP",
            id: "76417d51-a8c7-47d5-b7e2-28d89f0d438e"
        }
    }
};
export const paramDef = {
    type: "object",
    properties: {
        noteId: {
            type: "string",
            format: "misskey:id"
        },
        groupId: {
            type: "string",
            format: "misskey:id",
            nullable: true
        }
    },
    required: [
        "noteId"
    ]
};
export default define(meta, paramDef, async (ps, user)=>{
    // Get favoritee
    const note = await getNote(ps.noteId, user).catch((err)=>{
        if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") throw new ApiError(meta.errors.noSuchNote);
        throw err;
    });
    const group = await getGroupActor(ps.groupId, user);
    if (ps.groupId != null && group == null) throw new ApiError(meta.errors.noSuchGroup);
    // if already favorited
    const favorite = await NoteFavorites.findOneBy({
        noteId: note.id,
        ...group ? {
            groupId: group.id
        } : {
            userId: user.id,
            groupId: null
        }
    });
    if (favorite == null) {
        throw new ApiError(meta.errors.notFavorited);
    }
    // Delete favorite
    await NoteFavorites.delete(favorite.id);
});
