import { z } from 'zod';
import { globalOptionsZod } from '../../Command.js';
import request from '../../request.js';
import { formatting } from '../../utils/formatting.js';
import GraphCommand from "./GraphCommand.js";
export const periodBasedReportOptions = z.strictObject({
    ...globalOptionsZod.shape,
    output: z.enum(['json', 'csv']).optional().alias('o'),
    period: z.enum(['D7', 'D30', 'D90', 'D180']).alias('p')
});
export default class PeriodBasedReport extends GraphCommand {
    get allowedOutputs() {
        return ['json', 'csv'];
    }
    get schema() {
        return periodBasedReportOptions;
    }
    async commandAction(logger, args) {
        const endpoint = `${this.resource}/v1.0/reports/${this.usageEndpoint}(period='${formatting.encodeQueryParameter(args.options.period)}')`;
        await this.executeReport(endpoint, logger, args.options.output);
    }
    async executeReport(endPoint, logger, output) {
        const requestOptions = {
            url: endPoint,
            headers: {
                accept: 'application/json;odata.metadata=none'
            },
            responseType: 'json'
        };
        let res;
        try {
            res = await request.get(requestOptions);
        }
        catch (err) {
            this.handleRejectedODataJsonPromise(err);
            return;
        }
        let content;
        const cleanResponse = this.removeEmptyLines(res);
        if (output && output.toLowerCase() === 'json') {
            const reportData = this.getReport(cleanResponse);
            content = reportData;
        }
        else {
            content = cleanResponse;
        }
        await logger.log(content);
    }
    removeEmptyLines(input) {
        const rows = input.split('\n');
        const cleanRows = rows.filter(Boolean);
        return cleanRows.join('\n');
    }
    getReport(res) {
        const rows = res.split('\n');
        const jsonObj = [];
        const headers = rows[0].split(',');
        for (let i = 1; i < rows.length; i++) {
            const data = rows[i].split(',');
            const obj = {};
            for (let j = 0; j < data.length; j++) {
                obj[headers[j].trim()] = data[j].trim();
            }
            jsonObj.push(obj);
        }
        return jsonObj;
    }
}
//# sourceMappingURL=PeriodBasedReport.js.map