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

//#endregion
class GetEmployeeListQuery {
    constructor() {
        this.entityService = inject(AXPEntityService);
        this.employeeService = this.entityService
            .withEntity(`${RootConfig.module.name}.${RootConfig.entities.employee.name}`)
            .data();
    }
    async fetch(input) {
        // Extract employee-specific filters from AXPFilterClause format
        const extractedFilters = this.extractEmployeeFilters(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 employees from storage with entity filters
        const allEmployeesResult = await this.employeeService.query({
            skip: 0,
            take: 10000, // Get all employees for aggregation
            filter: entityFilters.length > 0
                ? {
                    logic: input.logic || 'and',
                    filters: entityFilters,
                }
                : undefined,
        });
        const allEmployees = allEmployeesResult.items;
        // Group employees by department and team
        const departmentGroups = new Map();
        for (const employee of allEmployees) {
            // Get department from position (assuming position has departmentId)
            const departmentId = employee.position?.departmentId || employee.departmentId || 'unknown';
            const departmentTitle = employee.position?.department?.title || 'Unknown Department';
            // Get team from team memberships (assuming employee has teamId or teamMemberships)
            const teamId = employee.teamId || employee.teamMemberships?.[0]?.teamId || undefined;
            const teamTitle = employee.team?.title || employee.teamMemberships?.[0]?.team?.title || undefined;
            const teamKey = teamId || 'no-team';
            if (!departmentGroups.has(departmentId)) {
                departmentGroups.set(departmentId, new Map());
            }
            const teamMap = departmentGroups.get(departmentId);
            if (!teamMap.has(teamKey)) {
                teamMap.set(teamKey, []);
            }
            teamMap.get(teamKey).push(employee);
        }
        // Aggregate data by department and team
        const aggregatedResults = [];
        for (const [departmentId, teamMap] of departmentGroups.entries()) {
            const firstEmployee = Array.from(teamMap.values())[0]?.[0];
            const departmentTitle = firstEmployee?.position?.department?.title || 'Unknown Department';
            for (const [teamKey, employees] of teamMap.entries()) {
                const teamId = teamKey !== 'no-team' ? teamKey : undefined;
                const teamTitle = teamKey !== 'no-team' ? employees[0]?.team?.title || employees[0]?.teamMemberships?.[0]?.team?.title : undefined;
                // Calculate average experience (years since hire date)
                const now = new Date();
                const experiences = employees
                    .map((emp) => {
                    if (!emp.hireDate)
                        return 0;
                    const hireDate = new Date(emp.hireDate);
                    const diffTime = Math.abs(now.getTime() - hireDate.getTime());
                    return diffTime / (1000 * 60 * 60 * 24 * 365.25); // Convert to years
                })
                    .filter((exp) => exp > 0);
                const averageExperience = experiences.length > 0 ? experiences.reduce((sum, exp) => sum + exp, 0) / experiences.length : 0;
                // Get unique employment types
                const employmentTypeSet = new Set();
                for (const employee of employees) {
                    if (employee.employmentType?.title) {
                        employmentTypeSet.add(employee.employmentType.title);
                    }
                }
                const employmentTypes = Array.from(employmentTypeSet).join(', ') || 'N/A';
                aggregatedResults.push({
                    departmentId,
                    departmentTitle,
                    teamId,
                    teamTitle,
                    employeeCount: employees.length,
                    employmentTypes,
                    averageExperience: Number(averageExperience.toFixed(2)),
                    totalEmployees: employees.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 employee-specific filters from AXPFilterClause format
     * Maps report parameter paths to employee entity field names
     */
    extractEmployeeFilters(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 employee-specific field mappings
            if (field === 'department') {
                // Department filter - can be array of IDs or single ID
                if (Array.isArray(value) && value.length > 0) {
                    filters.push({
                        field: 'position.departmentId', // Assuming position has departmentId
                        operator: { type: 'in' },
                        value: value,
                    });
                }
                else if (value) {
                    filters.push({
                        field: 'position.departmentId',
                        operator: { type: 'equal' },
                        value: value,
                    });
                }
            }
            else if (field === 'team') {
                // Team filter - can be array of IDs or single ID
                if (Array.isArray(value) && value.length > 0) {
                    filters.push({
                        field: 'teamId', // Assuming employee has teamId or teamMemberships
                        operator: { type: 'in' },
                        value: value,
                    });
                }
                else if (value) {
                    filters.push({
                        field: 'teamId',
                        operator: { type: 'equal' },
                        value: value,
                    });
                }
            }
            else if (field === 'employmentType') {
                // Employment type filter - skip 'all' value
                if (value && value !== 'all') {
                    filters.push({
                        field: 'employmentTypeId',
                        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: GetEmployeeListQuery, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetEmployeeListQuery, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetEmployeeListQuery, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }] });

export { GetEmployeeListQuery };
//# sourceMappingURL=acorex-connectivity-mock-get-employee-list.query-Ch-Vh5GE.mjs.map
