'use client';
import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
import { useModal } from '@faceless-ui/modal';
import { getTranslation } from '@payloadcms/translations';
import { useRouter, useSearchParams } from 'next/navigation.js';
import { formatAdminURL, mergeListSearchAndWhere } from 'payload/shared';
import * as qs from 'qs-esm';
import React from 'react';
import { toast } from 'sonner';
import { CheckboxInput } from '../../fields/Checkbox/Input.js';
import { useAuth } from '../../providers/Auth/index.js';
import { useConfig } from '../../providers/Config/index.js';
import { useLocale } from '../../providers/Locale/index.js';
import { useRouteCache } from '../../providers/RouteCache/index.js';
import { SelectAllStatus, useSelection } from '../../providers/Selection/index.js';
import { useTranslation } from '../../providers/Translation/index.js';
import { requests } from '../../utilities/api.js';
import { parseSearchParams } from '../../utilities/parseSearchParams.js';
import { shouldPermanentlyDelete } from '../../utilities/shouldPermanentlyDelete.js';
import { ConfirmationModal } from '../ConfirmationModal/index.js';
import { ListSelectionButton } from '../ListSelection/index.js';
import { Translation } from '../Translation/index.js';
import './index.scss';
/**
   * Whether the user has permission to permanently delete documents.
   * If provided, uses this instead of reading from auth context.
   */ /**
   * Whether the user has permission to trash (soft delete) documents.
   * If provided, uses this instead of reading from auth context.
   */ /**
   * When multiple DeleteMany components are rendered on the page, this will differentiate them.
   */ /**
   * When multiple PublishMany components are rendered on the page, this will differentiate them.
   */ export const DeleteMany = (props)=>{
    const { viewType } = props;
    const { collection: { slug, trash } = {}, hasDeletePermission: hasDeletePermissionFromProps, hasTrashPermission: hasTrashPermissionFromProps, modalPrefix } = props;
    const { permissions } = useAuth();
    const { count, selectAll, selectedIDs, toggleAll } = useSelection();
    const router = useRouter();
    const searchParams = useSearchParams();
    const { clearRouteCache } = useRouteCache();
    const collectionPermissions = permissions?.collections?.[slug];
    const hasDeletePermission = hasDeletePermissionFromProps !== undefined ? hasDeletePermissionFromProps : Boolean(collectionPermissions?.delete);
    const hasTrashPermission = hasTrashPermissionFromProps !== undefined ? hasTrashPermissionFromProps : hasDeletePermission;
    const selectingAll = selectAll === SelectAllStatus.AllAvailable;
    const ids = selectingAll ? [] : selectedIDs;
    const isTrashView = viewType === 'trash';
    const canShowDeleteButton = isTrashView ? hasDeletePermission : hasDeletePermission || hasTrashPermission;
    if (selectAll === SelectAllStatus.None || !canShowDeleteButton) {
        return null;
    }
    const baseWhere = parseSearchParams(searchParams)?.where;
    const finalWhere = viewType === 'trash' ? {
        and: [
            ...Array.isArray(baseWhere?.and) ? baseWhere.and : baseWhere ? [
                baseWhere
            ] : [],
            {
                deletedAt: {
                    exists: true
                }
            }
        ]
    } : baseWhere;
    return /*#__PURE__*/ _jsxDEV(React.Fragment, {
        children: /*#__PURE__*/ _jsxDEV(DeleteMany_v4, {
            afterDelete: ()=>{
                toggleAll();
                router.replace(qs.stringify({
                    ...parseSearchParams(searchParams),
                    page: selectAll ? '1' : undefined
                }, {
                    addQueryPrefix: true
                }));
                clearRouteCache();
            },
            hasDeletePermission: hasDeletePermission,
            hasTrashPermission: hasTrashPermission,
            modalPrefix: modalPrefix,
            search: parseSearchParams(searchParams)?.search,
            selections: {
                [slug]: {
                    all: selectAll === SelectAllStatus.AllAvailable,
                    ids,
                    totalCount: selectingAll ? count : ids.length
                }
            },
            trash: trash,
            viewType: viewType,
            where: finalWhere
        }, void 0, false, {
            fileName: "src/elements/DeleteMany/index.tsx",
            lineNumber: 101,
            columnNumber: 7
        }, this)
    }, void 0, false, {
        fileName: "src/elements/DeleteMany/index.tsx",
        lineNumber: 100,
        columnNumber: 5
    }, this);
};
/**
   * A callback function to be called after the delete request is completed.
   */ /**
   * Whether the user has permission to permanently delete documents.
   * When false, the "delete permanently" checkbox will be hidden.
   */ /**
   * Whether the user has permission to trash (soft delete) documents.
   * When false and hasDeletePermission is true, only permanent delete is available.
   */ /**
   * When multiple DeleteMany components are rendered on the page, this will differentiate them.
   */ /**
   * Optionally pass a search string to filter the documents to be deleted.
   *
   * This is intentionally passed as a prop so modals could pass in their own
   * search string that may not be stored in the URL.
   */ /**
   * An object containing the relationTo as the key and an object with the following properties:
   * - all: boolean
   * - totalCount: number
   * - ids: (string | number)[]
   */ /**
   * Optionally pass a where clause to filter the documents to be deleted.
   * This will be ignored if multiple relations are selected.
   *
   * This is intentionally passed as a prop so modals could pass in their own
   * where clause that may not be stored in the URL.
   */ /**
 * Handles polymorphic document delete operations.
 *
 * If you are deleting monomorphic documents, shape your `selections` to match the polymorphic structure.
 */ export function DeleteMany_v4({ afterDelete, hasDeletePermission = false, hasTrashPermission = false, modalPrefix, search, selections, trash, viewType, where }) {
    const { t } = useTranslation();
    const { config: { collections, routes: { api } } } = useConfig();
    const { code: locale } = useLocale();
    const { i18n } = useTranslation();
    const { openModal } = useModal();
    const [deletePermanently, setDeletePermanently] = React.useState(false);
    const confirmManyDeleteDrawerSlug = `${modalPrefix ? `${modalPrefix}-` : ''}confirm-delete-many-docs`;
    const handleDelete = React.useCallback(async ()=>{
        const deletingOneCollection = Object.keys(selections).length === 1;
        const result = {};
        for (const [relationTo, { all, ids = [] }] of Object.entries(selections)){
            const collectionConfig = collections.find(({ slug })=>slug === relationTo);
            if (collectionConfig) {
                let whereConstraint;
                if (all) {
                    // selecting all documents with optional where filter
                    if (deletingOneCollection && where) {
                        whereConstraint = viewType === 'trash' ? {
                            and: [
                                ...Array.isArray(where.and) ? where.and : [
                                    where
                                ],
                                {
                                    deletedAt: {
                                        exists: true
                                    }
                                }
                            ]
                        } : where;
                    } else {
                        whereConstraint = viewType === 'trash' ? {
                            and: [
                                {
                                    id: {
                                        not_equals: ''
                                    }
                                },
                                {
                                    deletedAt: {
                                        exists: true
                                    }
                                }
                            ]
                        } : {
                            id: {
                                not_equals: ''
                            }
                        };
                    }
                } else {
                    // selecting specific documents
                    whereConstraint = {
                        and: [
                            {
                                id: {
                                    in: ids
                                }
                            },
                            ...viewType === 'trash' ? [
                                {
                                    deletedAt: {
                                        exists: true
                                    }
                                }
                            ] : []
                        ]
                    };
                }
                const url = formatAdminURL({
                    apiRoute: api,
                    path: `/${relationTo}${qs.stringify({
                        limit: 0,
                        locale,
                        select: {},
                        where: mergeListSearchAndWhere({
                            collectionConfig,
                            search,
                            where: whereConstraint
                        }),
                        ...viewType === 'trash' ? {
                            trash: true
                        } : {}
                    }, {
                        addQueryPrefix: true
                    })}`
                });
                const permanentlyDelete = shouldPermanentlyDelete({
                    deletePermanently,
                    hasDeletePermission,
                    hasTrashPermission: Boolean(collectionConfig.trash) && hasTrashPermission,
                    isTrashView: viewType === 'trash'
                });
                const deleteManyResponse = permanentlyDelete ? await requests.delete(url, {
                    headers: {
                        'Accept-Language': i18n.language,
                        'Content-Type': 'application/json'
                    }
                }) : await requests.patch(url, {
                    body: JSON.stringify({
                        deletedAt: new Date().toISOString()
                    }),
                    headers: {
                        'Accept-Language': i18n.language,
                        'Content-Type': 'application/json'
                    }
                });
                try {
                    const { plural, singular } = collectionConfig.labels;
                    const json = await deleteManyResponse.json();
                    const deletedDocs = json?.docs.length || 0;
                    const successLabel = deletedDocs > 1 ? plural : singular;
                    if (deleteManyResponse.status < 400 || deletedDocs > 0) {
                        let successKey;
                        if (!permanentlyDelete) {
                            successKey = 'general:trashedCountSuccessfully';
                        } else if (viewType === 'trash' || hasDeletePermission && deletePermanently) {
                            successKey = 'general:permanentlyDeletedCountSuccessfully';
                        } else {
                            successKey = 'general:deletedCountSuccessfully';
                        }
                        toast.success(t(successKey, {
                            count: deletedDocs,
                            label: getTranslation(successLabel, i18n)
                        }));
                    }
                    if (json?.errors.length > 0) {
                        toast.error(json.message, {
                            description: json.errors.map((error)=>error.message).join('\n')
                        });
                    }
                    result[relationTo] = {
                        deletedCount: deletedDocs,
                        errors: json?.errors || null,
                        ids: json?.docs.map((doc)=>doc.id) || [],
                        totalCount: json.totalDocs
                    };
                    if (deleteManyResponse.status > 400 && json?.errors.length === 0) {
                        toast.error(t('error:unknown'));
                        result[relationTo].errors = [
                            t('error:unknown')
                        ];
                    }
                    continue;
                } catch (_err) {
                    toast.error(t('error:unknown'));
                    result[relationTo] = {
                        deletedCount: 0,
                        errors: [
                            _err
                        ],
                        ids: [],
                        totalCount: 0
                    };
                    continue;
                }
            }
        }
        if (typeof afterDelete === 'function') {
            afterDelete(result);
        }
    }, [
        selections,
        afterDelete,
        collections,
        deletePermanently,
        hasDeletePermission,
        hasTrashPermission,
        locale,
        search,
        api,
        i18n,
        viewType,
        where,
        t
    ]);
    const { label: labelString, labelCount } = Object.entries(selections).reduce((acc, [key, value], index, array)=>{
        const collectionConfig = collections.find(({ slug })=>slug === key);
        if (collectionConfig) {
            const labelCount = acc.labelCount === undefined ? value.totalCount : acc.labelCount;
            const collectionLabel = `${acc.labelCount !== undefined ? `${value.totalCount} ` : ''}${getTranslation(value.totalCount > 1 ? collectionConfig.labels.plural : collectionConfig.labels.singular, i18n)}`;
            let newLabel;
            if (index === array.length - 1 && index !== 0) {
                newLabel = `${acc.label} and ${collectionLabel}`;
            } else if (index > 0) {
                newLabel = `${acc.label}, ${collectionLabel}`;
            } else {
                newLabel = collectionLabel;
            }
            return {
                label: newLabel,
                labelCount
            };
        }
        return acc;
    }, {
        label: '',
        labelCount: undefined
    });
    return /*#__PURE__*/ _jsxDEV(React.Fragment, {
        children: [
            /*#__PURE__*/ _jsxDEV(ListSelectionButton, {
                "aria-label": t('general:delete'),
                className: "delete-documents__toggle",
                onClick: ()=>{
                    openModal(confirmManyDeleteDrawerSlug);
                },
                children: t('general:delete')
            }, void 0, false, {
                fileName: "src/elements/DeleteMany/index.tsx",
                lineNumber: 426,
                columnNumber: 7
            }, this),
            /*#__PURE__*/ _jsxDEV(ConfirmationModal, {
                body: /*#__PURE__*/ _jsxDEV(React.Fragment, {
                    children: [
                        /*#__PURE__*/ _jsxDEV("p", {
                            children: trash && hasTrashPermission ? viewType === 'trash' ? /*#__PURE__*/ _jsxDEV(Translation, {
                                elements: {
                                    '0': ({ children })=>/*#__PURE__*/ _jsxDEV("strong", {
                                            children: children
                                        }, void 0, false, {
                                            fileName: "src/elements/DeleteMany/index.tsx",
                                            lineNumber: 443,
                                            columnNumber: 46
                                        }, void 0),
                                    '1': ({ children })=>/*#__PURE__*/ _jsxDEV("strong", {
                                            children: children
                                        }, void 0, false, {
                                            fileName: "src/elements/DeleteMany/index.tsx",
                                            lineNumber: 444,
                                            columnNumber: 46
                                        }, void 0)
                                },
                                i18nKey: "general:aboutToPermanentlyDeleteTrash",
                                t: t,
                                variables: {
                                    count: labelCount ?? 0,
                                    label: labelString
                                }
                            }, void 0, false, {
                                fileName: "src/elements/DeleteMany/index.tsx",
                                lineNumber: 441,
                                columnNumber: 19
                            }, void 0) : t('general:aboutToTrashCount', {
                                count: labelCount,
                                label: labelString
                            }) : t('general:aboutToDeleteCount', {
                                count: labelCount,
                                label: labelString
                            })
                        }, void 0, false, {
                            fileName: "src/elements/DeleteMany/index.tsx",
                            lineNumber: 438,
                            columnNumber: 13
                        }, void 0),
                        trash && hasTrashPermission && hasDeletePermission && viewType !== 'trash' && /*#__PURE__*/ _jsxDEV("div", {
                            className: "delete-documents__checkbox",
                            children: /*#__PURE__*/ _jsxDEV(CheckboxInput, {
                                checked: deletePermanently,
                                id: "delete-forever",
                                label: t('general:deletePermanently'),
                                name: "delete-forever",
                                onToggle: (e)=>setDeletePermanently(e.target.checked)
                            }, void 0, false, {
                                fileName: "src/elements/DeleteMany/index.tsx",
                                lineNumber: 462,
                                columnNumber: 17
                            }, void 0)
                        }, void 0, false, {
                            fileName: "src/elements/DeleteMany/index.tsx",
                            lineNumber: 461,
                            columnNumber: 15
                        }, void 0)
                    ]
                }, void 0, true, {
                    fileName: "src/elements/DeleteMany/index.tsx",
                    lineNumber: 437,
                    columnNumber: 11
                }, void 0),
                confirmingLabel: t('general:deleting'),
                heading: t('general:confirmDeletion'),
                modalSlug: confirmManyDeleteDrawerSlug,
                onConfirm: handleDelete
            }, void 0, false, {
                fileName: "src/elements/DeleteMany/index.tsx",
                lineNumber: 435,
                columnNumber: 7
            }, this)
        ]
    }, void 0, true, {
        fileName: "src/elements/DeleteMany/index.tsx",
        lineNumber: 425,
        columnNumber: 5
    }, this);
}

//# sourceMappingURL=index.js.map