import {TransactType} from "./index";

export interface CharacterTable {
    clearOrCreateCharacterEditor(options: {userId: string, deleteFirst: boolean}): Promise<{inserted: number, deleted: number}>
}

export class CharacterTableImpl implements CharacterTable {
    private readonly _transact: TransactType

    constructor({transact}: { transact: TransactType }) {
        this._transact = transact
    }

    async clearOrCreateCharacterEditor(
        {userId, deleteFirst}: { userId: string; deleteFirst: boolean }): Promise<{ inserted: number, deleted: number }> {
        const result = {
            inserted: 0,
            deleted: 0,
        }
        await this._transact({
            readonly: false,
            async transaction(query) {
                result.deleted = deleteFirst
                    ? (await query("DELETE FROM character_creation WHERE id = $1", [userId])).rowCount
                    : 0
                result.inserted =
                    (await query("INSERT INTO character_creation (id) VALUES ($1) ON CONFLICT (id) DO NOTHING")).rowCount
            }
        })
        return result
    }
}