import { Brackets, In } from "typeorm";
import { Notes } from "../../../../models/index.js";
import define from "../../define.js";
function hasLuaFile(note) {
    return note.files?.some((file)=>file.name.toLowerCase().endsWith(".lua")) ?? false;
}
export const meta = {
    tags: [
        "notes"
    ],
    requireCredential: false,
    requireCredentialPrivateMode: true,
    res: {
        type: "array",
        optional: false,
        nullable: false,
        items: {
            type: "object",
            optional: false,
            nullable: false,
            ref: "Note"
        }
    }
};
export const paramDef = {
    type: "object",
    properties: {
        query: {
            type: "string",
            default: ""
        },
        limit: {
            type: "integer",
            minimum: 1,
            maximum: 50,
            default: 20
        },
        offset: {
            type: "integer",
            minimum: 0,
            default: 0
        }
    },
    required: []
};
export default define(meta, paramDef, async (ps, user)=>{
    const queryText = ps.query.trim();
    const query = Notes.createQueryBuilder("note").innerJoinAndSelect("note.user", "user").leftJoinAndSelect("note.reply", "reply").leftJoinAndSelect("note.renote", "renote").leftJoinAndSelect("reply.user", "replyUser").leftJoinAndSelect("renote.user", "renoteUser").where({
        visibility: In([
            "public",
            "home"
        ])
    }).andWhere("'{\"lua4frozen\"}' <@ note.tags").andWhere("note.fileIds != '{}'");
    if (queryText.length > 0) {
        query.andWhere(new Brackets((qb)=>{
            qb.where("note.text ILIKE :query", {
                query: `%${queryText}%`
            }).orWhere("user.usernameLower ILIKE :query", {
                query: `%${queryText.toLowerCase()}%`
            });
        }));
    }
    const notes = await query.orderBy("note.createdAt", "DESC").skip(ps.offset).take(ps.limit * 3).getMany();
    const packed = await Notes.packMany(notes, user);
    return packed.filter((note)=>hasLuaFile(note)).slice(0, ps.limit);
});
