"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.createPurchaseRouter = void 0;
const body_parser_1 = require("body-parser");
const express_1 = require("express");
const http_errors_1 = require("http-errors");
const purchase_1 = require("../function/purchase");
const validator_1 = require("./validator");
const createPurchaseRouter = ({ database, websocket }) => {
    const router = (0, express_1.Router)();
    router.post('/can-do-purchase', (0, body_parser_1.json)(), async (req, res, next) => {
        try {
            if (!(0, validator_1.isCanDoPurchaseRequest)(req.body)) {
                throw new http_errors_1.BadRequest();
            }
            if (req.body.type === 'googleplay' && !purchase_1.areGooglePlayPaymentsPossible) {
                res.json({ canDoPurchase: 'no because not supported by the server' });
                return;
            }
            const result = await database.transaction(async (transaction) => {
                const familyEntry = await (0, purchase_1.requireFamilyEntry)({
                    database,
                    deviceAuthToken: req.body.deviceAuthToken,
                    transaction
                });
                return (0, purchase_1.canDoNextPurchase)({
                    fullVersionUntil: parseInt(familyEntry.fullVersionUntil, 10),
                    fullVersionDebts: parseInt(familyEntry.fullVersionDebts, 10),
                });
            });
            res.json({
                canDoPurchase: result ? 'yes' : 'no due to old purchase',
                googlePlayPublicKey: purchase_1.googlePlayPublicKey
            });
        }
        catch (ex) {
            next(ex);
        }
    });
    router.post('/finish-purchase-by-google-play', (0, body_parser_1.json)(), async (req, res, next) => {
        try {
            if (!(0, validator_1.isFinishPurchaseByGooglePlayRequest)(req.body)) {
                throw new http_errors_1.BadRequest();
            }
            await database.transaction(async (transaction) => {
                const deviceEntryUnsafe = await database.device.findOne({
                    where: {
                        deviceAuthToken: req.body.deviceAuthToken
                    },
                    attributes: ['familyId'],
                    transaction
                });
                if (!deviceEntryUnsafe) {
                    throw new http_errors_1.Unauthorized();
                }
                const deviceEntry = {
                    familyId: deviceEntryUnsafe.familyId
                };
                if (!(0, purchase_1.isGooglePlayPurchaseSignatureValid)({
                    receipt: req.body.receipt,
                    signature: req.body.signature
                })) {
                    throw new http_errors_1.Conflict();
                }
                const receipt = JSON.parse(req.body.receipt);
                if (typeof receipt !== 'object') {
                    throw new http_errors_1.Conflict();
                }
                let type;
                if (receipt.productId === 'premium_year_2018') {
                    type = 'year';
                }
                else if (receipt.productId === 'premium_month_2018') {
                    type = 'month';
                }
                else {
                    throw new http_errors_1.Conflict();
                }
                const orderId = receipt.orderId;
                if (typeof orderId !== 'string') {
                    throw new http_errors_1.Conflict();
                }
                await (0, purchase_1.addPurchase)({
                    database,
                    familyId: deviceEntry.familyId,
                    type,
                    service: 'googleplay',
                    transactionId: orderId,
                    websocket,
                    transaction
                });
            });
            res.json({ ok: true });
        }
        catch (ex) {
            next(ex);
        }
    });
    return router;
};
exports.createPurchaseRouter = createPurchaseRouter;
//# sourceMappingURL=purchase.js.map