"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.backfill = void 0;
const index_1 = require("./../index");
const backend_core_1 = require("@devlego/backend-core");
const pro_1 = require("@devlego/pro");
const getOldestCreatedAt = (allApps) => {
    const timestamps = allApps
        .filter(app => !!app.createdAt)
        .map(app => app.createdAt)
        .sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
    if (timestamps.length) {
        return timestamps[0];
    }
};
const getMonthTimestamp = (monthString) => {
    const parts = monthString.split("-");
    const month = parseInt(parts[0]) - 1; // we already do +1 in month string calculation
    const year = parseInt(parts[1]);
    // using 0 as the day in next month gives us last day in previous month
    const date = new Date(year, month + 1, 0).getTime();
    const now = new Date().getTime();
    if (date > now) {
        return now;
    }
    else {
        return date;
    }
};
const backfill = (allApps) => __awaiter(void 0, void 0, void 0, function* () {
    const usage = yield pro_1.quotas.getQuotaUsage();
    const rows = usage.usageQuota.rows;
    let timestamp = index_1.DEFAULT_TIMESTAMP;
    const oldestAppTimestamp = getOldestCreatedAt(allApps);
    if (oldestAppTimestamp) {
        timestamp = oldestAppTimestamp;
    }
    yield backend_core_1.events.rows.created(rows, timestamp);
    for (const [monthString, quotas] of Object.entries(usage.monthly)) {
        if (monthString === "current") {
            continue;
        }
        const monthTimestamp = getMonthTimestamp(monthString);
        const queries = quotas.queries;
        yield backend_core_1.events.query.run(queries, monthTimestamp);
        const automations = quotas.automations;
        yield backend_core_1.events.automation.run(automations, monthTimestamp);
    }
    return usage;
});
exports.backfill = backfill;
