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

//#endregion
class GetLocationListQuery {
    constructor() {
        this.entityService = inject(AXPEntityService);
        this.locationService = this.entityService
            .withEntity(`${RootConfig.module.name}.${RootConfig.entities.location.name}`)
            .data();
    }
    async fetch(input) {
        // Extract location-specific filters from AXPFilterClause format
        const extractedFilters = this.extractLocationFilters(input.filters);
        // Separate custom filters from entity filters
        const entityFilters = [];
        if (extractedFilters && extractedFilters.length > 0) {
            for (const filter of extractedFilters) {
                entityFilters.push(filter);
            }
        }
        // Get all locations from storage with entity filters
        const allLocationsResult = await this.locationService.query({
            skip: 0,
            take: 10000, // Get all locations for aggregation
            filter: entityFilters.length > 0
                ? {
                    logic: input.logic || 'and',
                    filters: entityFilters,
                }
                : undefined,
        });
        const allLocations = allLocationsResult.items;
        // Group locations by country, province, and city
        const locationGroups = new Map();
        for (const location of allLocations) {
            // Get geographic information
            const countryId = location.countryId || 'unknown';
            const countryTitle = location.country?.title || 'Unknown Country';
            const provinceId = location.stateId || 'unknown';
            const provinceTitle = location.state?.title || 'Unknown Province';
            const cityId = location.cityId || 'unknown';
            const cityTitle = location.city?.title || 'Unknown City';
            // Create nested map structure: country -> province -> city -> locations[]
            if (!locationGroups.has(countryId)) {
                locationGroups.set(countryId, new Map());
            }
            const provinceMap = locationGroups.get(countryId);
            if (!provinceMap.has(provinceId)) {
                provinceMap.set(provinceId, new Map());
            }
            const cityMap = provinceMap.get(provinceId);
            if (!cityMap.has(cityId)) {
                cityMap.set(cityId, []);
            }
            cityMap.get(cityId).push(location);
        }
        // Aggregate data by country, province, and city
        const aggregatedResults = [];
        for (const [countryId, provinceMap] of locationGroups.entries()) {
            const firstLocation = Array.from(provinceMap.values())[0]?.values().next().value?.[0];
            const countryTitle = firstLocation?.country?.title || 'Unknown Country';
            for (const [provinceId, cityMap] of provinceMap.entries()) {
                const firstLocationInProvince = cityMap.values().next().value?.[0];
                const provinceTitle = firstLocationInProvince?.state?.title || 'Unknown Province';
                for (const [cityId, locations] of cityMap.entries()) {
                    const cityTitle = locations[0]?.city?.title || 'Unknown City';
                    aggregatedResults.push({
                        countryId,
                        countryTitle,
                        provinceId,
                        provinceTitle,
                        cityId,
                        cityTitle,
                        locationCount: locations.length,
                        totalLocations: locations.length,
                    });
                }
            }
        }
        // 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 location-specific filters from AXPFilterClause format
     * Maps report parameter paths to location entity field names
     */
    extractLocationFilters(parameters) {
        const filters = [];
        const paramsAny = parameters;
        if (!paramsAny?.filters || !Array.isArray(paramsAny.filters)) {
            console.log('⚠️ [extractLocationFilters] No filters array found or not an array');
            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 location-specific field mappings
            if (field === 'country') {
                // Country filter
                if (Array.isArray(value) && value.length > 0) {
                    filters.push({
                        field: 'countryId',
                        operator: { type: 'in' },
                        value: value,
                    });
                }
                else if (value) {
                    filters.push({
                        field: 'countryId',
                        operator: { type: 'equal' },
                        value: value,
                    });
                }
            }
            else if (field === 'province') {
                // Province/State filter
                if (Array.isArray(value) && value.length > 0) {
                    filters.push({
                        field: 'stateId',
                        operator: { type: 'in' },
                        value: value,
                    });
                }
                else if (value) {
                    filters.push({
                        field: 'stateId',
                        operator: { type: 'equal' },
                        value: value,
                    });
                    console.log('✅ [extractLocationFilters] Added province filter (equal):', value);
                }
            }
            else if (field === 'city') {
                if (Array.isArray(value) && value.length > 0) {
                    filters.push({
                        field: 'cityId',
                        operator: { type: 'in' },
                        value: value,
                    });
                }
                else if (value) {
                    filters.push({
                        field: 'cityId',
                        operator: { type: 'equal' },
                        value: value,
                    });
                }
            }
            else {
                // Direct field mapping
                filters.push({
                    field: field,
                    operator: operator,
                    value: value,
                });
            }
        }
        return filters;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetLocationListQuery, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetLocationListQuery, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetLocationListQuery, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }] });

export { GetLocationListQuery };
//# sourceMappingURL=acorex-connectivity-mock-get-location-list.query-Xbc6d8kb.mjs.map
