import { UmbEntityTrashedEvent } from './trash.event.js';
import { createExtensionApiByAlias } from '../../../extension-registry/index.js';
import { umbConfirmModal } from '../../../modal/index.js';
import { UMB_ACTION_EVENT_CONTEXT } from '../../../action/index.js';
import { UmbEntityActionBase, UmbRequestReloadStructureForEntityEvent } from '../../../entity-action/index.js';
import { UmbLocalizationController } from '../../../../../libs/localization-api/index.js';
/**
 * Entity action for trashing an item.
 * @class UmbTrashEntityAction
 * @augments {UmbEntityActionBase<MetaEntityActionTrashKind>}
 */
export class UmbTrashEntityAction extends UmbEntityActionBase {
    #localize = new UmbLocalizationController(this);
    /**
     * Executes the action.
     * @memberof UmbTrashEntityAction
     */
    async execute() {
        if (!this.args.unique)
            throw new Error('Cannot trash an item without a unique identifier.');
        const item = await this.#requestItem();
        await this._confirmTrash(item);
        const recycleBinRepository = await createExtensionApiByAlias(this, this.args.meta.recycleBinRepositoryAlias);
        const { error } = await recycleBinRepository.requestTrash({ unique: this.args.unique });
        if (error) {
            throw error;
        }
        this.#notify();
    }
    async _confirmTrash(item) {
        const headline = '#actions_trash';
        const message = '#defaultdialogs_confirmTrash';
        // TODO: handle items with variants
        await umbConfirmModal(this, {
            headline,
            content: this.#localize.string(message, item.name),
            color: 'danger',
            confirmLabel: '#actions_trash',
        });
    }
    async #requestItem() {
        if (!this.args.unique)
            throw new Error('Cannot trash an item without a unique identifier.');
        const itemRepository = await createExtensionApiByAlias(this, this.args.meta.itemRepositoryAlias);
        const { data } = await itemRepository.requestItems([this.args.unique]);
        const item = data?.[0];
        if (!item)
            throw new Error('Item not found.');
        return item;
    }
    async #notify() {
        const actionEventContext = await this.getContext(UMB_ACTION_EVENT_CONTEXT);
        if (!actionEventContext)
            throw new Error('Action event context is missing.');
        const event = new UmbRequestReloadStructureForEntityEvent({
            unique: this.args.unique,
            entityType: this.args.entityType,
        });
        actionEventContext.dispatchEvent(event);
        const trashedEvent = new UmbEntityTrashedEvent({
            unique: this.args.unique,
            entityType: this.args.entityType,
        });
        actionEventContext.dispatchEvent(trashedEvent);
    }
}
export { UmbTrashEntityAction as api };
