import { DriveFiles, UserGroups } from "../../../../../models/index.js";
import define from "../../../define.js";
import { ApiError } from "../../../error.js";
export const meta = {
    tags: [
        "groups"
    ],
    requireCredential: true,
    kind: "write:user-groups",
    description: "Update the properties of a group.",
    res: {
        type: "object",
        optional: false,
        nullable: false,
        ref: "UserGroup"
    },
    errors: {
        noSuchGroup: {
            message: "No such group.",
            code: "NO_SUCH_GROUP",
            id: "9081cda3-7a9e-4fac-a6ce-908d70f282f6"
        },
        noSuchFile: {
            message: "No such file.",
            code: "NO_SUCH_FILE",
            id: "45861e5e-75d4-4353-b8a9-a72fd2b4c62f"
        }
    }
};
export const paramDef = {
    type: "object",
    properties: {
        groupId: {
            type: "string",
            format: "misskey:id"
        },
        name: {
            type: "string",
            minLength: 1,
            maxLength: 100
        },
        username: {
            type: "string",
            pattern: "^[a-zA-Z0-9_]{1,64}$",
            nullable: true
        },
        allowCalls: {
            type: "boolean"
        },
        iconFileId: {
            type: "string",
            format: "misskey:id",
            nullable: true
        },
        symbolFileId: {
            type: "string",
            format: "misskey:id",
            nullable: true
        }
    },
    required: [
        "groupId",
        "name"
    ]
};
export default define(meta, paramDef, async (ps, me)=>{
    // Fetch the group
    const userGroup = await UserGroups.findOneBy({
        id: ps.groupId,
        userId: me.id
    });
    if (userGroup == null) {
        throw new ApiError(meta.errors.noSuchGroup);
    }
    const updates = {
        name: ps.name
    };
    if (ps.username !== undefined) updates.username = ps.username?.toLowerCase() ?? null;
    if (typeof ps.allowCalls === "boolean") updates.allowCalls = ps.allowCalls;
    if (ps.iconFileId !== undefined) {
        if (ps.iconFileId) {
            const file = await DriveFiles.findOneBy({
                id: ps.iconFileId,
                userId: me.id
            });
            if (!file) throw new ApiError(meta.errors.noSuchFile);
        }
        updates.iconFileId = ps.iconFileId;
    }
    if (ps.symbolFileId !== undefined) {
        if (ps.symbolFileId) {
            const file = await DriveFiles.findOneBy({
                id: ps.symbolFileId,
                userId: me.id
            });
            if (!file) throw new ApiError(meta.errors.noSuchFile);
        }
        updates.symbolFileId = ps.symbolFileId;
    }
    await UserGroups.update(userGroup.id, updates);
    return await UserGroups.pack(userGroup.id);
});
