import { Brackets } from "typeorm";
import define from "../../define.js";
import { ReversiGames } from "../../../../models/index.js";
import { makePaginationQuery } from "../../common/make-pagination-query.js";
export const meta = {
    tags: [
        "reversi"
    ],
    requireCredential: false,
    res: {
        type: "array",
        optional: false,
        nullable: false,
        items: {
            type: "object"
        }
    }
};
export const paramDef = {
    type: "object",
    properties: {
        limit: {
            type: "integer",
            minimum: 1,
            maximum: 100,
            default: 10
        },
        sinceId: {
            type: "string",
            format: "misskey:id"
        },
        untilId: {
            type: "string",
            format: "misskey:id"
        },
        my: {
            type: "boolean",
            default: false
        }
    },
    required: []
};
export default define(meta, paramDef, async (ps, user)=>{
    const query = makePaginationQuery(ReversiGames.createQueryBuilder("game"), ps.sinceId, ps.untilId).innerJoinAndSelect("game.user1", "user1").innerJoinAndSelect("game.user2", "user2");
    if (ps.my && user) {
        query.andWhere(new Brackets((qb)=>{
            qb.where("game.user1Id = :userId", {
                userId: user.id
            }).orWhere("game.user2Id = :userId", {
                userId: user.id
            });
        }));
    } else {
        query.andWhere("game.isStarted = TRUE");
    }
    const games = await query.take(ps.limit).getMany();
    return await Promise.all(games.map((game)=>ReversiGames.packLite(game)));
});
