"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.signInIntoFamily = void 0;
const http_errors_1 = require("http-errors");
const mail_1 = require("../../util/mail");
const token_1 = require("../../util/token");
const authentication_1 = require("../authentication");
const prepare_device_entry_1 = require("../device/prepare-device-entry");
const websocket_1 = require("../websocket");
const get_server_data_status_1 = require("../sync/get-server-data-status");
const clientdatastatus_1 = require("../../object/clientdatastatus");
const signInIntoFamily = async ({ database, eventHandler, mailAuthToken, newDeviceInfo, deviceName, websocket, clientLevel }) => {
    return database.transaction(async (transaction) => {
        const mailInfo = await (0, authentication_1.requireMailAndLocaleByAuthToken)({ database, mailAuthToken, transaction, invalidate: true });
        const userEntryUnsafe = await database.user.findOne({
            where: {
                mail: mailInfo.mail
            },
            attributes: ['familyId', 'userId'],
            transaction
        });
        if (!userEntryUnsafe) {
            throw new http_errors_1.Conflict();
        }
        const userEntry = {
            familyId: userEntryUnsafe.familyId,
            userId: userEntryUnsafe.userId
        };
        const deviceAuthToken = (0, token_1.generateAuthToken)();
        const deviceId = (0, token_1.generateIdWithinFamily)();
        await database.device.create((0, prepare_device_entry_1.prepareDeviceEntry)({
            familyId: userEntry.familyId,
            deviceId,
            userId: userEntry.userId,
            deviceName,
            deviceAuthToken,
            newDeviceInfo,
            isUserKeptSignedIn: true
        }), { transaction });
        // notify about changes
        await database.family.update({
            deviceListVersion: (0, token_1.generateVersionId)()
        }, {
            where: {
                familyId: userEntry.familyId
            },
            transaction
        });
        await (0, websocket_1.notifyClientsAboutChangesDelayed)({
            familyId: userEntry.familyId,
            websocket,
            database,
            generalLevel: 1,
            targetedLevels: new Map(),
            sourceDeviceId: deviceId,
            transaction
        });
        transaction.afterCommit(async () => {
            await (0, mail_1.sendDeviceLinkedMail)({
                receiver: mailInfo.mail,
                locale: mailInfo.locale,
                deviceName
            });
        });
        const data = await (0, get_server_data_status_1.generateServerDataStatus)({
            database,
            clientStatus: (0, clientdatastatus_1.createEmptyClientDataStatus)({ clientLevel }),
            familyId: userEntry.familyId,
            deviceId,
            transaction,
            eventHandler
        });
        return {
            deviceId,
            deviceAuthToken,
            data
        };
    });
};
exports.signInIntoFamily = signInIntoFamily;
//# sourceMappingURL=sign-in-into-family.js.map