"use strict";
/*
 * server component for the TimeLimit App
 * Copyright (C) 2019 - 2026 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.createFamily = createFamily;
const http_errors_1 = require("http-errors");
const get_server_data_status_1 = require("../sync/get-server-data-status");
const schema_1 = require("../../api/schema");
const user_1 = require("../../database/user");
const clientdatastatus_1 = require("../../object/clientdatastatus");
const token_1 = require("../../util/token");
const authentication_1 = require("../authentication");
const prepare_device_entry_1 = require("../device/prepare-device-entry");
async function createFamily({ database, eventHandler, mailAuthToken, firstParentDevice, password, timeZone, parentName, deviceName, clientLevel }) {
    (0, schema_1.assertPlaintextParentPasswordValid)(password);
    return database.transaction(async (transaction) => {
        const now = Date.now().toString(10);
        const mailInfo = await (0, authentication_1.requireMailAndLocaleByAuthToken)({ database, mailAuthToken, transaction, invalidate: true });
        // ensure that no family was created for this mail yet
        const existingUserEntry = await database.user.findOne({
            where: {
                mail: mailInfo.mail
            },
            transaction
        });
        if (existingUserEntry) {
            throw new http_errors_1.Conflict();
        }
        const familyId = (0, token_1.generateFamilyId)();
        const userId = (0, token_1.generateIdWithinFamily)();
        const deviceId = (0, token_1.generateIdWithinFamily)();
        const deviceAuthToken = (0, token_1.generateAuthToken)();
        // create family
        await database.family.create({
            familyId,
            name: '',
            createdAt: now,
            userListVersion: (0, token_1.generateVersionId)(),
            deviceListVersion: (0, token_1.generateVersionId)(),
            // 14 days demo version
            fullVersionUntil: (Date.now() + 1000 * 60 * 60 * 24 * 14).toString(10),
            hasFullVersion: true,
            nextServerKeyRequestSeq: '1',
            u2fKeysVersion: (0, token_1.generateVersionId)(),
            fullVersionDebts: '0'
        }, { transaction });
        // create parent user
        await database.user.create({
            familyId,
            userId,
            name: parentName,
            passwordHash: password.hash,
            secondPasswordHash: password.secondHash,
            secondPasswordSalt: password.secondSalt,
            type: 'parent',
            mail: mailInfo.mail,
            timeZone,
            disableTimelimitsUntil: '0',
            currentDevice: '',
            categoryForNotAssignedApps: '',
            relaxPrimaryDeviceRule: false,
            mailNotificationFlags: user_1.maxMailNotificationFlags,
            blockedTimes: '',
            flags: '0'
        }, { transaction });
        // add parent device
        await database.device.create((0, prepare_device_entry_1.prepareDeviceEntry)({
            familyId,
            deviceId,
            deviceName,
            newDeviceInfo: firstParentDevice,
            userId,
            deviceAuthToken,
            isUserKeptSignedIn: true
        }), { transaction });
        const data = await (0, get_server_data_status_1.generateServerDataStatus)({
            database,
            clientStatus: (0, clientdatastatus_1.createEmptyClientDataStatus)({ clientLevel }),
            familyId,
            deviceId,
            transaction,
            eventHandler
        });
        return {
            deviceAuthToken,
            deviceId,
            data
        };
    });
}
//# sourceMappingURL=create-family.js.map