var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
import { DeesElement, html, customElement, css, state, cssManager, } from '@design.estate/dees-element';
import * as appstate from '../../appstate.js';
import * as interfaces from '../../../dist_ts_interfaces/index.js';
import { viewHostCss } from '../shared/css.js';
import { appRouter } from '../../router.js';
let OpsViewDomains = (() => {
    let _classDecorators = [customElement('ops-view-domains')];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = DeesElement;
    let _domainsState_decorators;
    let _domainsState_initializers = [];
    let _domainsState_extraInitializers = [];
    var OpsViewDomains = class extends _classSuper {
        static { _classThis = this; }
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _domainsState_decorators = [state()];
            __esDecorate(this, null, _domainsState_decorators, { kind: "accessor", name: "domainsState", static: false, private: false, access: { has: obj => "domainsState" in obj, get: obj => obj.domainsState, set: (obj, value) => { obj.domainsState = value; } }, metadata: _metadata }, _domainsState_initializers, _domainsState_extraInitializers);
            __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            OpsViewDomains = _classThis = _classDescriptor.value;
            if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #domainsState_accessor_storage = __runInitializers(this, _domainsState_initializers, appstate.domainsStatePart.getState());
        get domainsState() { return this.#domainsState_accessor_storage; }
        set domainsState(value) { this.#domainsState_accessor_storage = value; }
        constructor() {
            super();
            __runInitializers(this, _domainsState_extraInitializers);
            const sub = appstate.domainsStatePart.select().subscribe((newState) => {
                this.domainsState = newState;
            });
            this.rxSubscriptions.push(sub);
        }
        async connectedCallback() {
            await super.connectedCallback();
            await appstate.domainsStatePart.dispatchAction(appstate.fetchDomainsAndProvidersAction, null);
        }
        static styles = [
            cssManager.defaultStyles,
            viewHostCss,
            css `
      .domainsContainer {
        display: flex;
        flex-direction: column;
        gap: 24px;
      }

      .sourceBadge {
        display: inline-flex;
        align-items: center;
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 500;
      }

      .sourceBadge.dcrouter {
        background: ${cssManager.bdTheme('#e0e7ff', '#1e1b4b')};
        color: ${cssManager.bdTheme('#3730a3', '#a5b4fc')};
      }

      .sourceBadge.provider {
        background: ${cssManager.bdTheme('#fef3c7', '#451a03')};
        color: ${cssManager.bdTheme('#92400e', '#fde047')};
      }
    `,
        ];
        render() {
            const domains = this.domainsState.domains;
            const providersById = new Map(this.domainsState.providers.map((p) => [p.id, p]));
            return html `
      <dees-heading level="3">Domains</dees-heading>
      <div class="domainsContainer">
        <dees-table
          .heading1=${'Domains'}
          .heading2=${'Domains under management — served by dcrouter (authoritative) or imported from a provider'}
          .data=${domains}
          .showColumnFilters=${true}
          .displayFunction=${(d) => ({
                Name: d.name,
                Source: this.renderSourceBadge(d, providersById),
                Authoritative: d.authoritative ? 'yes' : 'no',
                Nameservers: d.nameservers?.join(', ') || '-',
                'Last Synced': d.lastSyncedAt
                    ? new Date(d.lastSyncedAt).toLocaleString()
                    : '-',
            })}
          .dataActions=${[
                {
                    name: 'Add DcRouter Domain',
                    iconName: 'lucide:plus',
                    type: ['header'],
                    actionFunc: async () => {
                        await this.showCreateDcrouterDialog();
                    },
                },
                {
                    name: 'Import from Provider',
                    iconName: 'lucide:download',
                    type: ['header'],
                    actionFunc: async () => {
                        await this.showImportDialog();
                    },
                },
                {
                    name: 'Refresh',
                    iconName: 'lucide:rotateCw',
                    type: ['header'],
                    actionFunc: async () => {
                        await appstate.domainsStatePart.dispatchAction(appstate.fetchDomainsAndProvidersAction, null);
                    },
                },
                {
                    name: 'View Records',
                    iconName: 'lucide:list',
                    type: ['inRow', 'contextmenu'],
                    actionFunc: async (actionData) => {
                        const domain = actionData.item;
                        await appstate.domainsStatePart.dispatchAction(appstate.fetchDnsRecordsForDomainAction, { domainId: domain.id });
                        appRouter.navigateToView('domains', 'dns');
                    },
                },
                {
                    name: 'Sync Now',
                    iconName: 'lucide:rotateCw',
                    type: ['inRow', 'contextmenu'],
                    actionFunc: async (actionData) => {
                        const domain = actionData.item;
                        if (domain.source !== 'provider') {
                            const { DeesToast } = await import('@design.estate/dees-catalog');
                            DeesToast.show({
                                message: 'Sync only applies to provider-managed domains',
                                type: 'warning',
                                duration: 3000,
                            });
                            return;
                        }
                        await appstate.domainsStatePart.dispatchAction(appstate.syncDomainAction, {
                            id: domain.id,
                        });
                    },
                },
                {
                    name: 'Migrate',
                    iconName: 'lucide:arrow-right-left',
                    type: ['inRow', 'contextmenu'],
                    actionFunc: async (actionData) => {
                        const domain = actionData.item;
                        await this.showMigrateDialog(domain);
                    },
                },
                {
                    name: 'Delete',
                    iconName: 'lucide:trash2',
                    type: ['inRow', 'contextmenu'],
                    actionFunc: async (actionData) => {
                        const domain = actionData.item;
                        await this.deleteDomain(domain);
                    },
                },
            ]}
        ></dees-table>
      </div>
    `;
        }
        renderSourceBadge(d, providersById) {
            if (d.source === 'dcrouter') {
                return html `<span class="sourceBadge dcrouter">DcRouter</span>`;
            }
            const provider = d.providerId ? providersById.get(d.providerId) : undefined;
            return html `<span class="sourceBadge provider">${provider?.name || 'Provider'}</span>`;
        }
        async showCreateDcrouterDialog() {
            const { DeesModal } = await import('@design.estate/dees-catalog');
            DeesModal.createAndShow({
                heading: 'Add DcRouter Domain',
                content: html `
        <dees-form>
          <dees-input-text .key=${'name'} .label=${'FQDN'} .description=${'e.g. example.com'} .required=${true}></dees-input-text>
          <dees-input-text .key=${'description'} .label=${'Description'}></dees-input-text>
        </dees-form>
        <p style="margin-top: 12px; font-size: 12px; opacity: 0.7;">
          dcrouter will become the authoritative DNS server for this domain. You'll need to
          delegate the domain's nameservers to dcrouter to make this effective.
        </p>
      `,
                menuOptions: [
                    { name: 'Cancel', action: async (modalArg) => modalArg.destroy() },
                    {
                        name: 'Create',
                        action: async (modalArg) => {
                            const form = modalArg.shadowRoot
                                ?.querySelector('.content')
                                ?.querySelector('dees-form');
                            if (!form)
                                return;
                            const data = await form.collectFormData();
                            await appstate.domainsStatePart.dispatchAction(appstate.createDcrouterDomainAction, {
                                name: String(data.name),
                                description: data.description ? String(data.description) : undefined,
                            });
                            modalArg.destroy();
                        },
                    },
                ],
            });
        }
        async showImportDialog() {
            const providers = this.domainsState.providers;
            if (providers.length === 0) {
                const { DeesToast } = await import('@design.estate/dees-catalog');
                DeesToast.show({
                    message: 'Add a DNS provider first (Domains > Providers)',
                    type: 'warning',
                    duration: 3500,
                });
                return;
            }
            const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
            DeesModal.createAndShow({
                heading: 'Import Domains from Provider',
                content: html `
        <dees-form>
          <dees-input-dropdown
            .key=${'providerId'}
            .label=${'Provider'}
            .options=${providers.map((p) => ({ option: p.name, key: p.id }))}
            .required=${true}
          ></dees-input-dropdown>
          <dees-input-text
            .key=${'domainNames'}
            .label=${'Domain Names'}
            .description=${'Comma-separated FQDNs, e.g. example.com, foo.com'}
            .required=${true}
          ></dees-input-text>
        </dees-form>
        <p style="margin-top: 12px; font-size: 12px; opacity: 0.7;">
          Tip: use "List Provider Domains" to see what's available before typing.
        </p>
      `,
                menuOptions: [
                    { name: 'Cancel', action: async (modalArg) => modalArg.destroy() },
                    {
                        name: 'List Provider Domains',
                        action: async (_modalArg) => {
                            const form = _modalArg.shadowRoot
                                ?.querySelector('.content')
                                ?.querySelector('dees-form');
                            if (!form)
                                return;
                            const data = await form.collectFormData();
                            const providerKey = data.providerId?.key ?? data.providerId;
                            if (!providerKey) {
                                DeesToast.show({ message: 'Pick a provider first', type: 'warning', duration: 2500 });
                                return;
                            }
                            const result = await appstate.fetchProviderDomains(String(providerKey));
                            if (!result.success) {
                                DeesToast.show({
                                    message: result.message || 'Failed to fetch domains',
                                    type: 'error',
                                    duration: 4000,
                                });
                                return;
                            }
                            const list = (result.domains ?? []).map((d) => d.name).join(', ');
                            DeesToast.show({
                                message: `Provider has: ${list || '(none)'}`,
                                type: 'info',
                                duration: 8000,
                            });
                        },
                    },
                    {
                        name: 'Import',
                        action: async (modalArg) => {
                            const form = modalArg.shadowRoot
                                ?.querySelector('.content')
                                ?.querySelector('dees-form');
                            if (!form)
                                return;
                            const data = await form.collectFormData();
                            const providerKey = data.providerId?.key ?? data.providerId;
                            if (!providerKey) {
                                DeesToast.show({ message: 'Pick a provider', type: 'warning', duration: 2500 });
                                return;
                            }
                            const names = String(data.domainNames || '')
                                .split(',')
                                .map((s) => s.trim())
                                .filter(Boolean);
                            if (names.length === 0) {
                                DeesToast.show({ message: 'Enter at least one FQDN', type: 'warning', duration: 2500 });
                                return;
                            }
                            await appstate.domainsStatePart.dispatchAction(appstate.importDomainsFromProviderAction, { providerId: String(providerKey), domainNames: names });
                            modalArg.destroy();
                        },
                    },
                ],
            });
        }
        async showMigrateDialog(domain) {
            const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
            const providers = this.domainsState.providers;
            // Build target options based on current source
            const targetOptions = [];
            for (const p of providers) {
                // Skip current source
                if (p.builtIn && domain.source === 'dcrouter')
                    continue;
                if (!p.builtIn && domain.source === 'provider' && domain.providerId === p.id)
                    continue;
                const label = p.builtIn ? 'DcRouter (self)' : `${p.name} (${p.type})`;
                const key = p.builtIn ? 'dcrouter' : `provider:${p.id}`;
                targetOptions.push({ option: label, key });
            }
            if (targetOptions.length === 0) {
                DeesToast.show({
                    message: 'No migration targets available. Add a DNS provider first.',
                    type: 'warning',
                    duration: 3000,
                });
                return;
            }
            const currentLabel = domain.source === 'dcrouter'
                ? 'DcRouter (self)'
                : providers.find((p) => p.id === domain.providerId)?.name || 'Provider';
            DeesModal.createAndShow({
                heading: `Migrate: ${domain.name}`,
                content: html `
        <dees-form>
          <dees-input-text
            .key=${'currentSource'}
            .label=${'Current source'}
            .value=${currentLabel}
            .disabled=${true}
          ></dees-input-text>
          <dees-input-dropdown
            .key=${'target'}
            .label=${'Migrate to'}
            .description=${'Select the target DNS management'}
            .options=${targetOptions}
            .required=${true}
          ></dees-input-dropdown>
          <dees-input-checkbox
            .key=${'deleteExisting'}
            .label=${'Delete existing records at provider first'}
            .description=${'Removes all records at the provider before pushing migrated records'}
            .value=${true}
          ></dees-input-checkbox>
        </dees-form>
      `,
                menuOptions: [
                    { name: 'Cancel', action: async (m) => m.destroy() },
                    {
                        name: 'Migrate',
                        action: async (m) => {
                            const form = m.shadowRoot?.querySelector('.content')?.querySelector('dees-form');
                            if (!form)
                                return;
                            const data = await form.collectFormData();
                            const targetKey = typeof data.target === 'object' ? data.target.key : data.target;
                            if (!targetKey)
                                return;
                            let targetSource;
                            let targetProviderId;
                            if (targetKey === 'dcrouter') {
                                targetSource = 'dcrouter';
                            }
                            else {
                                targetSource = 'provider';
                                targetProviderId = targetKey.replace('provider:', '');
                            }
                            await appstate.domainsStatePart.dispatchAction(appstate.migrateDomainAction, {
                                id: domain.id,
                                targetSource,
                                targetProviderId,
                                deleteExistingProviderRecords: targetSource === 'provider' ? Boolean(data.deleteExisting) : false,
                            });
                            DeesToast.show({ message: `Domain ${domain.name} migrated successfully`, type: 'success', duration: 3000 });
                            m.destroy();
                        },
                    },
                ],
            });
        }
        async deleteDomain(domain) {
            const { DeesModal } = await import('@design.estate/dees-catalog');
            DeesModal.createAndShow({
                heading: `Delete domain ${domain.name}?`,
                content: html `
        <p>
          ${domain.source === 'provider'
                    ? 'This removes the domain and its cached records from dcrouter only. The zone at the provider is NOT touched.'
                    : 'This removes the domain and all of its DNS records from dcrouter. dcrouter will no longer answer queries for this domain after the next restart.'}
        </p>
      `,
                menuOptions: [
                    { name: 'Cancel', action: async (modalArg) => modalArg.destroy() },
                    {
                        name: 'Delete',
                        action: async (modalArg) => {
                            await appstate.domainsStatePart.dispatchAction(appstate.deleteDomainAction, {
                                id: domain.id,
                            });
                            modalArg.destroy();
                        },
                    },
                ],
            });
        }
        static {
            __runInitializers(_classThis, _classExtraInitializers);
        }
    };
    return OpsViewDomains = _classThis;
})();
export { OpsViewDomains };
//# sourceMappingURL=data:application/json;base64, 