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

//#endregion
class GetProductChartDataQuery {
    constructor() {
        this.entityService = inject(AXPEntityService);
        this.productService = this.entityService.withEntity(`${RootConfig.module.name}.${RootConfig.entities.product.name}`).data();
    }
    async fetch(input) {
        // Extract product-specific filters from AXPFilterClause format
        const extractedFilters = this.extractProductFilters(input.filters);
        // Separate custom filters from entity filters
        const entityFilters = [];
        let priceRangeFilter;
        if (extractedFilters && extractedFilters.length > 0) {
            for (const filter of extractedFilters) {
                if (filter.field === 'priceRange') {
                    priceRangeFilter = filter.value;
                }
                else {
                    entityFilters.push(filter);
                }
            }
        }
        // Get all products from storage with entity filters (no pagination for charts)
        const allProductsResult = await this.productService.query({
            skip: 0,
            take: 10000, // Get all products for aggregation
            filter: entityFilters.length > 0
                ? {
                    logic: input.logic || 'and',
                    filters: entityFilters,
                }
                : undefined,
        });
        let allProducts = allProductsResult.items;
        // Apply custom price range filter after fetching
        if (priceRangeFilter && priceRangeFilter !== 'all') {
            allProducts = this.applyPriceRangeFilter(allProducts, priceRangeFilter);
        }
        // Group products by brand
        const brandGroups = new Map();
        for (const product of allProducts) {
            const brandKey = product.brand?.title || product.brandId || 'Unknown';
            if (!brandGroups.has(brandKey)) {
                brandGroups.set(brandKey, []);
            }
            brandGroups.get(brandKey).push(product);
        }
        // Aggregate data by brand for chart
        const chartResults = [];
        for (const [brandName, products] of brandGroups.entries()) {
            chartResults.push({
                brand: brandName,
                productCount: products.length,
            });
        }
        return {
            items: chartResults,
        };
    }
    //#region ----   Filter Extraction   ----
    /**
     * Extract product-specific filters from AXPFilterClause format
     * Maps report parameter paths to product entity field names
     */
    extractProductFilters(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 product-specific field mappings
            if (field === 'brand') {
                // Brand filter - can be array of IDs or single ID
                if (Array.isArray(value) && value.length > 0) {
                    filters.push({
                        field: 'brandId',
                        operator: { type: 'in' },
                        value: value,
                    });
                }
                else if (value) {
                    filters.push({
                        field: 'brandId',
                        operator: { type: 'equal' },
                        value: value,
                    });
                }
            }
            else if (field === 'category') {
                // Category filter - can be array of IDs or single ID
                if (Array.isArray(value) && value.length > 0) {
                    filters.push({
                        field: 'categoryIds',
                        operator: { type: 'contains' },
                        value: value[0], // Use first category for contains check
                    });
                }
                else if (value) {
                    filters.push({
                        field: 'categoryIds',
                        operator: { type: 'contains' },
                        value: value,
                    });
                }
            }
            else if (field === 'status') {
                // Status filter - skip 'all' value
                if (value && value !== 'all') {
                    filters.push({
                        field: 'statusId',
                        operator: { type: 'equal' },
                        value: value,
                    });
                }
            }
            else if (field === 'priceRange') {
                // Price range filter - custom logic handled in query
                filters.push({
                    field: 'priceRange',
                    operator: { type: 'equal' },
                    value: value,
                });
            }
            else if (field === 'startDate' || field === 'endDate') {
                // Date filters - can be handled if needed
                // For now, skip as they might not be directly on product entity
            }
            else {
                // Direct field mapping
                filters.push({
                    field: field,
                    operator: operator,
                    value: value,
                });
            }
        }
        return filters;
    }
    //#endregion
    //#region ----   Custom Filter Handlers   ----
    /**
     * Apply custom price range filter to products
     */
    applyPriceRangeFilter(products, priceRange) {
        return products.filter((product) => {
            const price = product.basePrice || 0;
            switch (priceRange) {
                case 'under-50':
                    return price < 50;
                case '50-100':
                    return price >= 50 && price < 100;
                case '100-500':
                    return price >= 100 && price < 500;
                case '500-1000':
                    return price >= 500 && price < 1000;
                case 'over-1000':
                    return price >= 1000;
                default:
                    return true;
            }
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetProductChartDataQuery, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetProductChartDataQuery, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetProductChartDataQuery, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }] });

export { GetProductChartDataQuery };
//# sourceMappingURL=acorex-connectivity-mock-get-product-chart-data.query-m8_ME45B.mjs.map
