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 GetProductListQuery {
    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
        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
        const aggregatedResults = [];
        for (const [brandName, products] of brandGroups.entries()) {
            const prices = products.map((p) => p.basePrice || 0).filter((p) => p > 0);
            const totalValue = prices.reduce((sum, price) => sum + price, 0);
            const productCount = products.length;
            const averagePrice = productCount > 0 ? totalValue / productCount : 0;
            const minPrice = prices.length > 0 ? Math.min(...prices) : 0;
            const maxPrice = prices.length > 0 ? Math.max(...prices) : 0;
            // Get unique categories
            const categorySet = new Set();
            for (const product of products) {
                if (product.categories && Array.isArray(product.categories)) {
                    for (const cat of product.categories) {
                        if (cat.title) {
                            categorySet.add(cat.title);
                        }
                    }
                }
            }
            const categories = Array.from(categorySet).join(', ');
            // Get brand ID from first product
            const brandId = products[0]?.brandId || products[0]?.brand?.id;
            // Get manufacturer from first product (assuming all products in a brand have same manufacturer)
            const manufacturerName = products[0]?.manufacturer?.title || products[0]?.manufacturerId || 'Unknown';
            const manufacturerId = products[0]?.manufacturerId || products[0]?.manufacturer?.id;
            aggregatedResults.push({
                brand: brandName,
                brandId,
                manufacturer: manufacturerName,
                manufacturerId,
                productCount,
                totalValue: Number(totalValue.toFixed(2)),
                averagePrice: Number(averagePrice.toFixed(2)),
                minPrice: Number(minPrice.toFixed(2)),
                maxPrice: Number(maxPrice.toFixed(2)),
                categories,
            });
        }
        // Apply sorting if provided
        if (input.sort && input.sort.length > 0) {
            aggregatedResults.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;
                    if (aValue < bValue)
                        return -1 * dir;
                    if (aValue > bValue)
                        return 1 * dir;
                }
                return 0;
            });
        }
        // Apply pagination
        const skip = input.skip || 0;
        const take = input.take || 10;
        const total = aggregatedResults.length;
        const items = aggregatedResults.slice(skip, skip + take);
        return {
            items,
            total,
        };
    }
    //#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: GetProductListQuery, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetProductListQuery, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetProductListQuery, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }] });

export { GetProductListQuery };
//# sourceMappingURL=acorex-connectivity-mock-get-product-list.query-DzkssYRw.mjs.map
