import { db } from "../../db/postgre.js";
import { ReversiGame } from "../entities/reversi-game.js";
import { Users } from "../index.js";
import { genId } from "../../misc/gen-id.js";
function createdAtFromId(id) {
    const time = parseInt(id.slice(0, 8), 36);
    if (Number.isNaN(time)) return new Date().toISOString();
    return new Date(time + 946684800000).toISOString();
}
function assertBw(bw) {
    return bw === "1" || bw === "2" ? bw : "random";
}
export const ReversiGameRepository = db.getRepository(ReversiGame).extend({
    async packDetail (src) {
        const game = typeof src === "object" ? src : await this.findOneOrFail({
            where: {
                id: src
            },
            relations: {
                user1: true,
                user2: true
            }
        });
        const user1 = await Users.pack(game.user1 ?? game.user1Id, null, {
            detail: false
        });
        const user2 = await Users.pack(game.user2 ?? game.user2Id, null, {
            detail: false
        });
        return {
            id: game.id,
            createdAt: createdAtFromId(game.id),
            startedAt: game.startedAt?.toISOString() ?? null,
            endedAt: game.endedAt?.toISOString() ?? null,
            isStarted: game.isStarted,
            isEnded: game.isEnded,
            form1: game.form1,
            form2: game.form2,
            user1Ready: game.user1Ready,
            user2Ready: game.user2Ready,
            user1Id: game.user1Id,
            user2Id: game.user2Id,
            user1,
            user2,
            winnerId: game.winnerId,
            winner: game.winnerId ? [
                user1,
                user2
            ].find((u)=>u.id === game.winnerId) ?? null : null,
            surrenderedUserId: game.surrenderedUserId,
            timeoutUserId: game.timeoutUserId,
            black: game.black,
            bw: assertBw(game.bw),
            isLlotheo: game.isLlotheo,
            canPutEverywhere: game.canPutEverywhere,
            loopedBoard: game.loopedBoard,
            timeLimitForEachTurn: game.timeLimitForEachTurn,
            noIrregularRules: game.noIrregularRules,
            logs: game.logs,
            map: game.map
        };
    },
    async packLite (src) {
        const detail = await this.packDetail(src);
        const { logs, map, form1, form2, user1Ready, user2Ready, ...lite } = detail;
        return lite;
    },
    genId
});
