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/tenant-management';

//#endregion
class GetTenantUserDistributionQuery {
    constructor() {
        this.entityService = inject(AXPEntityService);
        this.tenantService = this.entityService
            .withEntity(`${RootConfig.module.name}.${RootConfig.entities.tenant.name}`)
            .data();
        this.tenantUserService = this.entityService
            .withEntity(`${RootConfig.module.name}.${RootConfig.entities.tenantUser.name}`)
            .data();
    }
    async fetch(input) {
        // Extract filters from AXPFilterClause format
        const extractedFilters = this.extractTenantFilters(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 tenants
        const tenantsResult = await this.tenantService.query({
            skip: 0,
            take: 10000,
            filter: entityFilters.length > 0
                ? {
                    logic: filterLogic,
                    filters: entityFilters,
                }
                : undefined,
        });
        let tenants = tenantsResult.items;
        // Apply date range filter if provided
        if (dateRangeFilter) {
            tenants = this.applyDateRangeFilter(tenants, dateRangeFilter);
        }
        // Get all tenant users
        const tenantUsersResult = await this.tenantUserService.query({
            skip: 0,
            take: 10000,
        });
        const tenantUsers = tenantUsersResult.items;
        // Build results for each tenant
        const results = [];
        for (const tenant of tenants) {
            // Get tenant's users
            const tenantUsersList = tenantUsers.filter((tu) => tu.tenantId === tenant.id);
            // Count active and inactive users
            const activeUsers = tenantUsersList.filter((tu) => tu.statusId === AXPSystemStatusType.Active);
            const inactiveUsers = tenantUsersList.filter((tu) => tu.statusId !== AXPSystemStatusType.Active);
            // Calculate utilization percentage
            const maxUsers = tenant.maxUsers;
            const utilizationPercent = maxUsers && maxUsers > 0 ? Math.round((tenantUsersList.length / maxUsers) * 100) : 0;
            results.push({
                tenantId: tenant.id,
                tenantName: tenant.title,
                tenantStatus: tenant.statusId || 'Unknown',
                totalUsersCount: tenantUsersList.length,
                activeUsersCount: activeUsers.length,
                inactiveUsersCount: inactiveUsers.length,
                maxUsers: maxUsers,
                utilizationPercent: utilizationPercent,
                registrationDate: tenant.registrationDate,
                registrationDateStr: tenant.registrationDate?.toISOString(),
            });
        }
        // 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;
                    if (aValue < bValue)
                        return -1 * dir;
                    if (aValue > bValue)
                        return 1 * dir;
                }
                return 0;
            });
        }
        else {
            // Default sort by tenant name
            results.sort((a, b) => a.tenantName.localeCompare(b.tenantName));
        }
        // 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 tenant-specific filters from AXPFilterClause format
     * Maps report parameter paths to tenant entity field names
     */
    extractTenantFilters(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 tenant-specific field mappings
            if (field === 'tenantId') {
                // Tenant ID filter - can be array of IDs or single ID
                if (Array.isArray(value) && value.length > 0) {
                    filters.push({
                        field: 'id',
                        operator: { type: 'in' },
                        value: value,
                    });
                }
                else if (value) {
                    filters.push({
                        field: 'id',
                        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 tenants
     */
    applyDateRangeFilter(tenants, dateRange) {
        if (!dateRange || !dateRange.start || !dateRange.end) {
            return tenants;
        }
        const startDate = new Date(dateRange.start);
        const endDate = new Date(dateRange.end);
        endDate.setHours(23, 59, 59, 999);
        return tenants.filter((tenant) => {
            if (!tenant.registrationDate)
                return false;
            const regDate = new Date(tenant.registrationDate);
            return regDate >= startDate && regDate <= endDate;
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetTenantUserDistributionQuery, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetTenantUserDistributionQuery, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: GetTenantUserDistributionQuery, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }] });

export { GetTenantUserDistributionQuery };
//# sourceMappingURL=acorex-connectivity-mock-get-tenant-user-distribution.query-CZXvavUh.mjs.map
