"use strict";
/*
 * server component for the TimeLimit App
 * Copyright (C) 2019 - 2022 Jonas Lochmann
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.dispatchChildSignIn = void 0;
const action_1 = require("../../../../action");
const setdeviceuser_1 = require("../dispatch-parent-action/setdeviceuser");
const illegal_state_1 = require("../exception/illegal-state");
const premium_1 = require("../exception/premium");
const dispatchChildSignIn = async ({ deviceId, childUserId, cache }) => {
    if (!cache.hasFullVersion) {
        throw new premium_1.PremiumVersionMissingException();
    }
    await (0, setdeviceuser_1.dispatchSetDeviceUser)({
        action: new action_1.SetDeviceUserAction({
            deviceId,
            userId: childUserId
        }),
        cache
    });
    const userEntryUnsafe = await cache.database.user.findOne({
        where: {
            familyId: cache.familyId,
            type: 'child',
            userId: childUserId
        },
        transaction: cache.transaction,
        attributes: [
            'currentDevice'
        ]
    });
    if (!userEntryUnsafe) {
        throw new illegal_state_1.SourceUserNotFoundException();
    }
    if (userEntryUnsafe.currentDevice === deviceId) {
        // unassign to prevent way aroundprimary device rule
        await cache.database.user.update({
            currentDevice: ''
        }, {
            where: {
                familyId: cache.familyId,
                type: 'child',
                userId: childUserId
            },
            transaction: cache.transaction
        });
        cache.invalidiateUserList = true;
    }
    cache.incrementTriggeredSyncLevel(1);
};
exports.dispatchChildSignIn = dispatchChildSignIn;
//# sourceMappingURL=childsignin.js.map