import * as i0 from '@angular/core';
import { inject, Injectable } from '@angular/core';
import { AXPEntityService } from '@acorex/platform/layout/entity';
import { AXPSystemStatusType } from '@acorex/platform/common';
import { RootConfig } from '@acorex/modules/subscription-management';
import { RootConfig as RootConfig$1 } from '@acorex/modules/tenant-management';

//#endregion
class GetSubscriptionsTimelineQuery {
    constructor() {
        this.entityService = inject(AXPEntityService);
        this.subscriptionService = this.entityService
            .withEntity(`${RootConfig.module.name}.${RootConfig.entities.subscription.name}`)
            .data();
        this.tenantService = this.entityService
            .withEntity(`${RootConfig$1.module.name}.${RootConfig$1.entities.tenant.name}`)
            .data();
    }
    async fetch(input) {
        // Extract filters from AXPFilterClause format
        const extractedFilters = this.extractSubscriptionFilters(input.filters);
        const filterLogic = input.filters?.logic || input.logic || 'and';
        // Separate custom filters from entity filters
        const entityFilters = [];
        let dateRangeFilter;
        if (extractedFilters && extractedFilters.length > 0) {
            for (const filter of extractedFilters) {
                if (filter.field === 'dateRange') {
                    dateRangeFilter = filter.value;
                }
                else {
                    entityFilters.push(filter);
                }
            }
        }
        // Get all subscriptions
        const subscriptionsResult = await this.subscriptionService.query({
            skip: 0,
            take: 10000,
            filter: entityFilters.length > 0
                ? {
                    logic: filterLogic,
                    filters: entityFilters,
                }
                : undefined,
        });
        let subscriptions = subscriptionsResult.items.filter((s) => s.subscriberType === 'Tenant');
        // Get all tenants for lookup
        const tenantsResult = await this.tenantService.query({
            skip: 0,
            take: 10000,
        });
        const tenants = tenantsResult.items;
        const tenantMap = new Map(tenants.map((t) => [t.id, t]));
        // Apply date range filter if provided
        if (dateRangeFilter) {
            subscriptions = this.applyDateRangeFilter(subscriptions, dateRangeFilter);
        }
        const now = new Date();
        // Build results
        const results = [];
        for (const subscription of subscriptions) {
            const startDate = new Date(subscription.startDate);
            const endDate = subscription.endDate ? new Date(subscription.endDate) : undefined;
            // Calculate duration in days
            const durationDays = endDate
                ? Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24))
                : Math.ceil((now.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
            // Extract time period info from start date
            const year = startDate.getFullYear();
            const month = startDate.getMonth() + 1;
            const monthName = startDate.toLocaleString('en-US', { month: 'long' });
            const quarter = Math.ceil(month / 3);
            const quarterName = `Q${quarter}`;
            // Check if subscription is currently active
            const isActive = subscription.statusId === AXPSystemStatusType.Active &&
                startDate <= now &&
                (!endDate || endDate >= now);
            // Get tenant name
            const tenant = tenantMap.get(subscription.subscriberId);
            results.push({
                subscriptionId: subscription.id,
                subscriptionTitle: subscription.title || `${tenant?.title || 'Unknown'} - ${subscription.plan?.title || 'Unknown Plan'}`,
                tenantId: subscription.subscriberId,
                tenantName: tenant?.title || 'Unknown',
                planId: subscription.planId,
                planName: subscription.plan?.title || 'Unknown',
                status: subscription.statusId || 'Unknown',
                startDate: startDate,
                startDateStr: startDate.toISOString(),
                endDate: endDate,
                endDateStr: endDate?.toISOString(),
                durationDays: durationDays,
                month: monthName,
                monthNumber: month,
                quarter: quarterName,
                year: year,
                isActive: isActive,
            });
        }
        // Apply sorting if provided
        if (input.sort && input.sort.length > 0) {
            results.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;
                    if (aValue === undefined && bValue === undefined)
                        continue;
                    if (aValue === undefined)
                        return 1 * dir;
                    if (bValue === undefined)
                        return -1 * dir;
                    // Handle date comparison
                    if (field === 'startDate') {
                        const aDate = a.startDate.getTime();
                        const bDate = b.startDate.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 start date descending (newest first)
            results.sort((a, b) => {
                return b.startDate.getTime() - a.startDate.getTime();
            });
        }
        // Apply pagination
        const skip = input.skip || 0;
        const take = input.take || 10;
        const total = results.length;
        const items = results.slice(skip, skip + take);
        return {
            items,
            total,
        };
    }
    //#region ----   Filter Extraction   ----
    /**
     * Extract subscription-specific filters from AXPFilterClause format
     * Maps report parameter paths to subscription entity field names
     */
    extractSubscriptionFilters(parameters) {
        const filters = [];
        const paramsAny = parameters;
        if (!paramsAny?.filters || !Array.isArray(paramsAny.filters)) {
            return filters;
        }
        for (const filter of paramsAny.filters) {
            if (!filter?.field || filter?.value === undefined || filter?.value === null) {
                continue;
            }
            const field = filter.field;
            const value = filter.value;
            const operator = filter.operator || { type: 'equal' };
            // Handle subscription-specific field mappings
            if (field === 'planId') {
                // Plan ID filter - can be array of IDs or single ID
                if (Array.isArray(value) && value.length > 0) {
                    filters.push({
                        field: 'planId',
                        operator: { type: 'in' },
                        value: value,
                    });
                }
                else if (value) {
                    filters.push({
                        field: 'planId',
                        operator: { type: 'equal' },
                        value: value,
                    });
                }
            }
            else if (field === 'statusId') {
                // Status filter - skip 'all' value
                if (value && value !== 'all') {
                    filters.push({
                        field: 'statusId',
                        operator: { type: 'equal' },
                        value: value,
                    });
                }
            }
            else if (field === 'dateRange') {
                // Date range filter - custom logic handled in query
                filters.push({
                    field: 'dateRange',
                    operator: { type: 'equal' },
                    value: value,
                });
            }
            else {
                // Direct field mapping
                filters.push({
                    field: field,
                    operator: operator,
                    value: value,
                });
            }
        }
        return filters;
    }
    //#endregion
    //#region ----   Custom Filter Handlers   ----
    /**
     * Apply date range filter to subscriptions
     */
    applyDateRangeFilter(subscriptions, dateRange) {
        if (!dateRange || !dateRange.start || !dateRange.end) {
            return subscriptions;
        }
        const startDate = new Date(dateRange.start);
        const endDate = new Date(dateRange.end);
        endDate.setHours(23, 59, 59, 999);
        return subscriptions.filter((subscription) => {
            const subStartDate = new Date(subscription.startDate);
            const subEndDate = subscription.endDate ? new Date(subscription.endDate) : null;
            // Check if subscription overlaps with the date range
            return ((subStartDate >= startDate && subStartDate <= endDate) ||
                (subEndDate && subEndDate >= startDate && subEndDate <= endDate) ||
                (subStartDate <= startDate && (!subEndDate || subEndDate >= endDate)));
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetSubscriptionsTimelineQuery, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetSubscriptionsTimelineQuery, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetSubscriptionsTimelineQuery, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }] });

export { GetSubscriptionsTimelineQuery };
//# sourceMappingURL=acorex-connectivity-mock-get-subscriptions-timeline.query-DBEEbeiS.mjs.map
