"use strict";
const api_types_1 = require("@n8n/api-types");
const di_1 = require("@n8n/di");
const luxon_1 = require("luxon");
const n8n_workflow_1 = require("n8n-workflow");
const zod_1 = require("zod");
const bad_request_error_1 = require("../../../../errors/response-errors/bad-request.error");
const forbidden_error_1 = require("../../../../errors/response-errors/forbidden.error");
const insights_service_1 = require("../../../../modules/insights/insights.service");
const global_middleware_1 = require("../../shared/middlewares/global.middleware");
const dateFilterValidationSchema = zod_1.z
    .object({
    startDate: zod_1.z.coerce.date().optional(),
    endDate: zod_1.z.coerce.date().optional(),
})
    .refine((data) => {
    if (data.startDate && data.endDate) {
        return data.startDate <= data.endDate;
    }
    return true;
}, {
    message: 'endDate must be the same as or after startDate',
    path: ['endDate'],
});
module.exports = {
    getInsightsSummary: [
        (0, global_middleware_1.publicApiScope)('insights:read'),
        async (req, res) => {
            const query = api_types_1.InsightsDateFilterDto.safeParse(req.query);
            if (!query.success) {
                throw new bad_request_error_1.BadRequestError(query.error.errors.map(({ message }) => message).join('; '));
            }
            const validation = dateFilterValidationSchema.safeParse(query.data);
            if (!validation.success) {
                throw new bad_request_error_1.BadRequestError(validation.error.errors.map(({ message }) => message).join('; '));
            }
            const endDate = query.data.endDate ?? new Date();
            const startDate = query.data.startDate ?? luxon_1.DateTime.now().minus({ days: 7 }).toJSDate();
            try {
                di_1.Container.get(insights_service_1.InsightsService).validateDateFiltersLicense({ startDate, endDate });
            }
            catch (error) {
                if (error instanceof n8n_workflow_1.UserError) {
                    throw new forbidden_error_1.ForbiddenError(error.message);
                }
                throw error;
            }
            const summary = await di_1.Container.get(insights_service_1.InsightsService).getInsightsSummary({
                startDate,
                endDate,
                projectId: query.data.projectId,
            });
            return res.json(summary);
        },
    ],
};
//# sourceMappingURL=insights.handler.js.map