var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * @fileoverview Archive Configuration Resource Component
 *
 * Dashboard resource wrapper for the "Configuration" tab in the Archiving application.
 * Delegates all rendering to the reusable mj-archive-config-admin component from
 * @memberjunction/ng-archive-manager.
 *
 * Beyond rendering, this wrapper reports a READ-ONLY summary of the archiving
 * configuration to the AI agent (policy/entity counts, load state) and exposes a
 * single read-only refresh tool. The wrapper owns its summary context by querying
 * the archive entities directly — the inner admin component only loads entities
 * for the currently-selected policy, so cross-policy counts live here.
 *
 * 🔒 SAFETY BOUNDARY (READ-ONLY): this surface NEVER exposes policy mutation to
 * the agent. The following are intentionally NOT wired as client tools:
 * ModifyArchivePolicy / create / edit / delete configurations or entities,
 * RunArchiveNow / execute, PurgeArchivedData, and any save path. The agent can
 * read counts and request a context refresh — nothing more. Saves happen only
 * via direct user interaction with the inner admin UI.
 */
import { Component, ViewChild } from '@angular/core';
import { RegisterClass } from '@memberjunction/global';
import { RunView } from '@memberjunction/core';
import { BaseResourceComponent } from '@memberjunction/ng-shared';
import { ArchiveConfigAdminComponent } from '@memberjunction/ng-archive-manager';
import { buildArchiveConfigAgentContext, ARCHIVE_NAME_LIST_CAP, } from '../archive-agent-context';
import * as i0 from "@angular/core";
import * as i1 from "@memberjunction/ng-archive-manager";
import * as i2 from "@memberjunction/ng-ui-components";
/** Active policy statuses — anything other than 'Disabled' counts as active. */
const DISABLED_STATUS = 'disabled';
let ArchiveConfigResourceComponent = class ArchiveConfigResourceComponent extends BaseResourceComponent {
    /** Reference to the inner admin component — used to read its public load state. */
    configAdmin;
    /** Wrapper-owned summary counts (queried directly across all policies). */
    policyCount = 0;
    activePolicyCount = 0;
    entitiesUnderArchive = 0;
    /** Bounded policy + archived-entity names for the agent context. */
    policyNames = [];
    archivedEntityNames = [];
    async ngAfterViewInit() {
        await this.loadSummaryCounts();
        this.publishAgentContext();
        this.registerAgentClientTools();
        this.NotifyLoadComplete();
    }
    ngOnDestroy() {
        super.ngOnDestroy();
    }
    async GetResourceDisplayName(_data) {
        return 'Archive Configuration';
    }
    async GetResourceIconClass(_data) {
        return 'fa-solid fa-sliders';
    }
    // ========================================
    // AI AGENT CONTEXT & CLIENT TOOLS (READ-ONLY)
    // ========================================
    /**
     * Publish the current Archive Configuration summary to the AI agent.
     * Read-only — describes policy/entity counts and load state only.
     */
    publishAgentContext() {
        const input = {
            PolicyCount: this.policyCount,
            ActivePolicyCount: this.activePolicyCount,
            EntitiesUnderArchive: this.entitiesUnderArchive,
            PolicyNames: this.policyNames,
            ArchivedEntityNames: this.archivedEntityNames,
            IsLoading: this.configAdmin?.IsLoading ?? false,
        };
        this.navigationService.SetAgentContext(this, buildArchiveConfigAgentContext(input));
    }
    /**
     * Register the read-only client tools for this surface.
     *
     * 🔒 Only a refresh tool is exposed. No policy create/edit/delete, no archive
     * execution, no purge — those are deliberately absent (see SAFETY BOUNDARY).
     */
    registerAgentClientTools() {
        this.navigationService.SetAgentClientTools(this, [
            {
                Name: 'RefreshArchiveConfig',
                Description: 'Reload the archive configuration summary (policy and entity counts). Read-only — does not modify any policy.',
                ParameterSchema: { type: 'object', properties: {} },
                Handler: async () => this.toolRefreshArchiveConfig(),
            },
        ]);
    }
    /** Re-query the summary counts and re-publish context. Never throws. */
    async toolRefreshArchiveConfig() {
        try {
            await this.loadSummaryCounts();
            this.publishAgentContext();
            return {
                Success: true,
                Data: {
                    PolicyCount: this.policyCount,
                    ActivePolicyCount: this.activePolicyCount,
                    EntitiesUnderArchive: this.entitiesUnderArchive,
                    PolicyNames: this.policyNames.slice(0, ARCHIVE_NAME_LIST_CAP),
                    ArchivedEntityNames: this.archivedEntityNames.slice(0, ARCHIVE_NAME_LIST_CAP),
                },
            };
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to refresh archive configuration.';
            return { Success: false, ErrorMessage: message };
        }
    }
    /**
     * Query the archive entities directly to compute cross-policy summary counts.
     * The inner admin component only loads entities for the selected policy, so the
     * wrapper owns these aggregate counts. Batched into a single RunViews call.
     */
    async loadSummaryCounts() {
        const rv = RunView.FromMetadataProvider(this.ProviderToUse);
        const [configResult, entityResult] = await rv.RunViews([
            {
                EntityName: 'MJ: Archive Configurations',
                ExtraFilter: '',
                Fields: ['ID', 'Name', 'Status'],
                OrderBy: 'Name',
                ResultType: 'simple',
            },
            {
                EntityName: 'MJ: Archive Configuration Entities',
                ExtraFilter: '',
                Fields: ['ID', 'Entity'],
                OrderBy: 'Entity',
                ResultType: 'simple',
            },
        ]);
        const configs = configResult.Success ? configResult.Results : [];
        this.policyCount = configs.length;
        this.activePolicyCount = configs.filter((c) => String(c['Status'] ?? '').toLowerCase() !== DISABLED_STATUS).length;
        this.policyNames = configs
            .map((c) => String(c['Name'] ?? '').trim())
            .filter((n) => !!n);
        const entities = entityResult.Success ? entityResult.Results : [];
        this.entitiesUnderArchive = entities.length;
        // De-duplicate entity names (a single entity can appear under multiple policies).
        this.archivedEntityNames = Array.from(new Set(entities.map((e) => String(e['Entity'] ?? '').trim()).filter((n) => !!n)));
    }
    static ɵfac = /*@__PURE__*/ (() => { let ɵArchiveConfigResourceComponent_BaseFactory; return function ArchiveConfigResourceComponent_Factory(__ngFactoryType__) { return (ɵArchiveConfigResourceComponent_BaseFactory || (ɵArchiveConfigResourceComponent_BaseFactory = i0.ɵɵgetInheritedFactory(ArchiveConfigResourceComponent)))(__ngFactoryType__ || ArchiveConfigResourceComponent); }; })();
    static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: ArchiveConfigResourceComponent, selectors: [["app-archive-config-resource"]], viewQuery: function ArchiveConfigResourceComponent_Query(rf, ctx) { if (rf & 1) {
            i0.ɵɵviewQuery(ArchiveConfigAdminComponent, 5);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.configAdmin = _t.first);
        } }, standalone: false, features: [i0.ɵɵInheritDefinitionFeature], decls: 4, vars: 2, consts: [["Title", "Archive Configuration", "Icon", "fa-solid fa-sliders", "Subtitle", "Configure entity archiving policies and schedules"], [3, "Flex", "Padding"]], template: function ArchiveConfigResourceComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelementStart(0, "mj-page-layout");
            i0.ɵɵelement(1, "mj-page-header", 0);
            i0.ɵɵelementStart(2, "mj-page-body", 1);
            i0.ɵɵelement(3, "mj-archive-config-admin");
            i0.ɵɵelementEnd()();
        } if (rf & 2) {
            i0.ɵɵadvance(2);
            i0.ɵɵproperty("Flex", true)("Padding", false);
        } }, dependencies: [i1.ArchiveConfigAdminComponent, i2.MJPageLayoutComponent, i2.MJPageHeaderComponent, i2.MJPageBodyComponent], styles: ["[_nghost-%COMP%] { display: block; height: 100%; width: 100%; }"] });
};
ArchiveConfigResourceComponent = __decorate([
    RegisterClass(BaseResourceComponent, 'ArchiveConfigResource')
], ArchiveConfigResourceComponent);
export { ArchiveConfigResourceComponent };
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ArchiveConfigResourceComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'app-archive-config-resource', template: `
        <mj-page-layout>
            <mj-page-header
                Title="Archive Configuration"
                Icon="fa-solid fa-sliders"
                Subtitle="Configure entity archiving policies and schedules">
            </mj-page-header>
            <mj-page-body [Flex]="true" [Padding]="false">
                <mj-archive-config-admin></mj-archive-config-admin>
            </mj-page-body>
        </mj-page-layout>
    `, styles: [":host { display: block; height: 100%; width: 100%; }"] }]
    }], null, { configAdmin: [{
            type: ViewChild,
            args: [ArchiveConfigAdminComponent]
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(ArchiveConfigResourceComponent, { className: "ArchiveConfigResourceComponent", filePath: "src/Archiving/components/archive-config-resource.component.ts", lineNumber: 56 }); })();
export function LoadArchiveConfigResource() {
    // Prevents tree-shaking
}
//# sourceMappingURL=archive-config-resource.component.js.map