import define from "../../../../define.js";
import { ApiError } from "../../../../error.js";
import { DriveFiles, UserEmojis, UserGroups } from "../../../../../../models/index.js";
import { genId } from "../../../../../../misc/gen-id.js";
import { getEmojiSize } from "../../../../../../misc/emoji-meta.js";
import { clearGroupEmojiCache } from "../../../../../../misc/populate-emojis.js";
function normalizeMimeType(type) {
    const mime = type?.split(";")[0]?.trim().toLowerCase();
    return mime && mime.length <= 64 ? mime : null;
}
export const meta = {
    tags: [
        "groups"
    ],
    requireCredential: true,
    kind: "write:user-groups",
    errors: {
        noSuchGroup: {
            message: "No such group.",
            code: "NO_SUCH_GROUP",
            id: "ab752eba-3f77-4746-b805-1457719f648d"
        },
        noSuchFile: {
            message: "No such file.",
            code: "NO_SUCH_FILE",
            id: "be2812bf-55c0-4fd9-8d1b-813578fc81f9"
        },
        alreadyExists: {
            message: "Group emoji already exists.",
            code: "ALREADY_EXISTS",
            id: "7957d717-e009-47c8-b32d-37a13afed4db"
        }
    }
};
export const paramDef = {
    type: "object",
    properties: {
        groupId: {
            type: "string",
            format: "misskey:id"
        },
        name: {
            type: "string",
            pattern: "^[a-z0-9_]{1,64}$"
        },
        fileId: {
            type: "string",
            format: "misskey:id"
        },
        glyph: {
            type: "boolean",
            default: false
        }
    },
    required: [
        "groupId",
        "name",
        "fileId"
    ]
};
export default define(meta, paramDef, async (ps, me)=>{
    const group = await UserGroups.findOneBy({
        id: ps.groupId,
        userId: me.id
    });
    if (!group) throw new ApiError(meta.errors.noSuchGroup);
    const file = await DriveFiles.findOneBy({
        id: ps.fileId,
        userId: me.id
    });
    if (!file || !file.type.startsWith("image/")) throw new ApiError(meta.errors.noSuchFile);
    const exists = await UserEmojis.findOneBy({
        name: ps.name,
        userGroupId: group.id
    });
    if (exists) throw new ApiError(meta.errors.alreadyExists);
    const size = await getEmojiSize(file.url).catch(()=>({
            width: null,
            height: null
        }));
    const emoji = await UserEmojis.insert({
        id: genId(),
        createdAt: new Date(),
        name: ps.name,
        userId: null,
        userGroupId: group.id,
        originalUrl: file.url,
        publicUrl: file.webpublicUrl ?? file.url,
        type: normalizeMimeType(file.webpublicType ?? file.type),
        glyph: ps.glyph,
        width: size.width || null,
        height: size.height || null
    }).then((x)=>UserEmojis.findOneByOrFail(x.identifiers[0]));
    await clearGroupEmojiCache(emoji.name, group.username);
    return {
        id: emoji.id,
        name: emoji.name,
        url: emoji.publicUrl || emoji.originalUrl,
        glyph: emoji.glyph,
        glyphUrl: emoji.glyph ? emoji.originalUrl : null,
        width: emoji.width,
        height: emoji.height
    };
});
