import define from "../../define.js";
import { ApiError } from "../../error.js";
import { getUser } from "../../common/getters.js";
import { CallBlockings, Users } from "../../../../models/index.js";
import { HOUR } from "../../../../const.js";
import { genId } from "../../../../misc/gen-id.js";
import { getGroupActor } from "../../common/get-group-actor.js";
export const meta = {
    tags: [
        "account"
    ],
    limit: {
        duration: HOUR,
        max: 100
    },
    requireCredential: true,
    kind: "write:blocks",
    errors: {
        noSuchUser: {
            message: "No such user.",
            code: "NO_SUCH_USER",
            id: "e476b7c0-03fd-44d3-8de2-efc43b15b7e0"
        },
        blockeeIsYourself: {
            message: "Blockee is yourself.",
            code: "BLOCKEE_IS_YOURSELF",
            id: "ee4c68c6-2a3d-4e13-8842-d4e7a341f109"
        },
        alreadyBlocking: {
            message: "You are already rejecting calls from that user.",
            code: "ALREADY_CALL_BLOCKING",
            id: "9601ea36-97cd-4232-b2d8-326e42e15df4"
        },
        noSuchGroup: {
            message: "No such group.",
            code: "NO_SUCH_GROUP",
            id: "1d7a15c6-41e5-4e5c-9ce5-a59b83a3b1ee"
        }
    },
    res: {
        type: "object",
        optional: false,
        nullable: false,
        ref: "UserDetailedNotMe"
    }
};
export const paramDef = {
    type: "object",
    properties: {
        userId: {
            type: "string",
            format: "misskey:id"
        },
        groupId: {
            type: "string",
            format: "misskey:id",
            nullable: true
        }
    },
    required: [
        "userId"
    ]
};
export default define(meta, paramDef, async (ps, user)=>{
    const blocker = await Users.findOneByOrFail({
        id: user.id
    });
    const group = await getGroupActor(ps.groupId, user);
    if (ps.groupId != null && group == null) throw new ApiError(meta.errors.noSuchGroup);
    if (group == null && user.id === ps.userId) {
        throw new ApiError(meta.errors.blockeeIsYourself);
    }
    const blockee = await getUser(ps.userId).catch((e)=>{
        if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") throw new ApiError(meta.errors.noSuchUser);
        throw e;
    });
    const exist = await CallBlockings.exist({
        where: {
            blockeeId: blockee.id,
            ...group ? {
                groupId: group.id
            } : {
                blockerId: blocker.id,
                groupId: null
            }
        }
    });
    if (exist) {
        throw new ApiError(meta.errors.alreadyBlocking);
    }
    await CallBlockings.insert({
        id: genId(),
        createdAt: new Date(),
        blockerId: blocker.id,
        blockeeId: blockee.id,
        groupId: group?.id ?? null,
        blocker,
        blockee
    });
    return await Users.pack(blockee.id, blocker, {
        detail: true
    });
});
