"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TrafficDataUsageStore = void 0;
const TABLE = 'stat_traffic_usage';
const COLUMNS = ['day', 'traffic_group', 'status_code_series', 'count'];
const toRow = (trafficDataUsage) => {
    return {
        day: trafficDataUsage.day,
        traffic_group: trafficDataUsage.trafficGroup,
        status_code_series: trafficDataUsage.statusCodeSeries,
        count: trafficDataUsage.count,
    };
};
const mapRow = (row) => {
    return {
        day: row.day,
        trafficGroup: row.traffic_group,
        statusCodeSeries: row.status_code_series,
        count: Number.parseInt(row.count),
    };
};
class TrafficDataUsageStore {
    constructor(db, getLogger) {
        this.db = db;
        this.logger = getLogger('traffic-data-usage-store.ts');
    }
    async get(key) {
        const row = await this.db
            .table(TABLE)
            .select()
            .where({
            day: key.day,
            traffic_group: key.trafficGroup,
            status_code_series: key.statusCodeSeries,
        })
            .first();
        return mapRow(row);
    }
    async getAll(query = {}) {
        const rows = await this.db.select(COLUMNS).where(query).from(TABLE);
        return rows.map(mapRow);
    }
    async exists(key) {
        const result = await this.db.raw(`SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE 
                day = ? AND
                traffic_group = ? AND
                status_code_series ?) AS present`, [key.day, key.trafficGroup, key.statusCodeSeries]);
        const { present } = result.rows[0];
        return present;
    }
    async delete(key) {
        await this.db(TABLE)
            .where({
            day: key.day,
            traffic_group: key.trafficGroup,
            status_code_series: key.statusCodeSeries,
        })
            .del();
    }
    async deleteAll() {
        await this.db(TABLE).del();
    }
    destroy() { }
    async upsert(trafficDataUsage) {
        const row = toRow(trafficDataUsage);
        await this.db(TABLE)
            .insert(row)
            .onConflict(['day', 'traffic_group', 'status_code_series'])
            .merge({
            count: this.db.raw('stat_traffic_usage.count + EXCLUDED.count'),
        });
    }
    async getTrafficDataUsageForPeriod(period) {
        const rows = await this.db(TABLE).whereRaw(`to_char(day, 'YYYY-MM') = ?`, [period]);
        return rows.map(mapRow);
    }
}
exports.TrafficDataUsageStore = TrafficDataUsageStore;
//# sourceMappingURL=traffic-data-usage-store.js.map