import * as i0 from '@angular/core';
import { inject, Injectable } from '@angular/core';
import { AXPEntityService } from '@acorex/platform/layout/entity';
import { RootConfig } from '@acorex/modules/application-management';

//#endregion
class GetApplicationVersionsTimelineQuery {
    constructor() {
        this.entityService = inject(AXPEntityService);
        this.appVersionService = this.entityService
            .withEntity(`${RootConfig.module.name}.${RootConfig.entities.appVersion.name}`)
            .data();
    }
    async fetch(input) {
        // Get all app versions from storage
        const allVersionsResult = await this.appVersionService.query({
            skip: 0,
            take: 10000, // Get all versions for aggregation
            filter: input.filters && input.filters.length > 0
                ? {
                    logic: input.logic || 'and',
                    filters: input.filters,
                }
                : undefined,
        });
        let allVersions = allVersionsResult.items;
        // Apply date range filter if provided
        if (input.filters) {
            for (const filter of input.filters) {
                if (filter.field === 'dateRange' && filter.value) {
                    allVersions = this.applyDateRangeFilter(allVersions, filter.value);
                }
                if (filter.field === 'versionNumber' && filter.value) {
                    allVersions = this.applyVersionNumberFilter(allVersions, filter.value);
                }
            }
        }
        // Group versions by time period (month/quarter/year)
        const periodGroups = new Map();
        for (const version of allVersions) {
            const publishDate = new Date(version.publishDate);
            const year = publishDate.getFullYear();
            const month = publishDate.getMonth() + 1;
            const quarter = Math.ceil(month / 3);
            const monthName = publishDate.toLocaleString('en-US', { month: 'long' });
            const quarterName = `Q${quarter}`;
            const periodKey = `${year}-${String(month).padStart(2, '0')}`;
            if (!periodGroups.has(periodKey)) {
                periodGroups.set(periodKey, []);
            }
            periodGroups.get(periodKey).push(version);
        }
        // Create timeline results
        const timelineResults = [];
        for (const version of allVersions) {
            const publishDate = new Date(version.publishDate);
            const year = publishDate.getFullYear();
            const month = publishDate.getMonth() + 1;
            const quarter = Math.ceil(month / 3);
            const monthName = publishDate.toLocaleString('en-US', { month: 'long' });
            const quarterName = `Q${quarter}`;
            const periodKey = `${year}-${String(month).padStart(2, '0')}`;
            const versionsInPeriod = periodGroups.get(periodKey)?.length || 0;
            timelineResults.push({
                versionNumber: version.versionNumber,
                publishDate: version.publishDate,
                publishDateObj: publishDate,
                year,
                month: monthName,
                monthNumber: month,
                quarter: quarterName,
                versionCount: versionsInPeriod,
            });
        }
        // Apply sorting if provided
        if (input.sort && input.sort.length > 0) {
            timelineResults.sort((a, b) => {
                for (const sortField of input.sort) {
                    const field = sortField.field;
                    const aValue = a[field];
                    const bValue = b[field];
                    const dir = sortField.dir === 'asc' ? 1 : -1;
                    // Handle undefined values
                    if (aValue === undefined && bValue === undefined)
                        continue;
                    if (aValue === undefined)
                        return 1 * dir;
                    if (bValue === undefined)
                        return -1 * dir;
                    // Handle date comparison
                    if (field === 'publishDateObj') {
                        const aDate = a.publishDateObj.getTime();
                        const bDate = b.publishDateObj.getTime();
                        if (aDate < bDate)
                            return -1 * dir;
                        if (aDate > bDate)
                            return 1 * dir;
                        continue;
                    }
                    if (aValue < bValue)
                        return -1 * dir;
                    if (aValue > bValue)
                        return 1 * dir;
                }
                return 0;
            });
        }
        else {
            // Default sort by publish date descending (newest first)
            timelineResults.sort((a, b) => {
                return b.publishDateObj.getTime() - a.publishDateObj.getTime();
            });
        }
        // Apply pagination
        const skip = input.skip || 0;
        const take = input.take || 10;
        const total = timelineResults.length;
        const items = timelineResults.slice(skip, skip + take);
        return {
            items,
            total,
        };
    }
    //#region ----   Custom Filter Handlers   ----
    /**
     * Apply date range filter to versions
     */
    applyDateRangeFilter(versions, dateRange) {
        if (!dateRange || !dateRange.start || !dateRange.end) {
            return versions;
        }
        const startDate = new Date(dateRange.start);
        const endDate = new Date(dateRange.end);
        endDate.setHours(23, 59, 59, 999); // Include the entire end date
        return versions.filter((version) => {
            const publishDate = new Date(version.publishDate);
            return publishDate >= startDate && publishDate <= endDate;
        });
    }
    /**
     * Apply version number filter to versions
     */
    applyVersionNumberFilter(versions, versionNumber) {
        if (!versionNumber) {
            return versions;
        }
        const searchTerm = versionNumber.toLowerCase().trim();
        return versions.filter((version) => {
            return version.versionNumber.toLowerCase().includes(searchTerm);
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetApplicationVersionsTimelineQuery, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetApplicationVersionsTimelineQuery, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetApplicationVersionsTimelineQuery, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }] });

export { GetApplicationVersionsTimelineQuery };
//# sourceMappingURL=acorex-connectivity-mock-get-application-versions-timeline.query-BHjQYTyZ.mjs.map
