import { isWorkspaceOwner } from './auth-service.js';
const DENIAL = 'Only the uploader or a workspace owner can delete assets in the shared Assets folder.';
/**
 * Delete authorization for the workspace-wide Assets store (codex-review P1 / D2).
 *
 * `workspace_wide` grants every member write (upload) access, so deletion needs
 * a tighter rule than folder-write: only the asset's uploader (recorded
 * `uploader_user_id`) or a workspace owner may delete it. Returns a denial
 * message, or `null` when the delete is allowed.
 *
 * Pass `filename` for single-file deletes (the filename route): the gate then
 * keys on the row for THAT file, and a legacy file with no index row is
 * owner-only — so a member can't delete a co-located legacy blob just by owning
 * a different indexed asset under the same entity (codex P1). Omit `filename`
 * for whole-entity deletes (gate on every indexed row).
 *
 * Scope: only gates `workspace_wide` folders. Non-workspace_wide folders return
 * `null` here (normal folder-write semantics already applied upstream).
 * Open-mode / API-key callers (`user` undefined) are unrestricted. An entity
 * with no indexed assets in the shared store is unexpected → owner-only.
 */
export function assetDeleteDenial(index, repoConfig, user, repo, entityType, entityId, filename) {
    if (!repoConfig?.workspace_wide)
        return null;
    if (!user)
        return null;
    const owner = isWorkspaceOwner(user.role);
    if (!index)
        return owner ? null : DENIAL;
    let rows = index.listByOwner(repo, entityType, entityId);
    if (filename !== undefined) {
        // Single-file delete: only the row for this exact file is relevant. No
        // matching row = a legacy/un-indexed blob → owner-only (can't be claimed
        // by owning a sibling asset under the same entity).
        rows = rows.filter(r => r.filename === filename);
        if (rows.length === 0)
            return owner ? null : DENIAL;
    }
    else if (rows.length === 0) {
        return owner ? null : DENIAL;
    }
    return rows.every(r => index.canDelete(r.assetId, user.id, owner)) ? null : DENIAL;
}
/**
 * Delete/move authorization for an asset addressed by its immutable `assetId`
 * (the asset-manager by-id routes; serves ANY indexed owner shape, including
 * legacy entity-owned stragglers). Same uploader/owner gate as
 * {@link assetDeleteDenial}, but keyed directly on the asset row rather than an
 * entity coordinate. Only gates `workspace_wide` folders; open-mode callers are
 * unrestricted. A missing row resolves owner-only via `index.canDelete`.
 */
export function assetDeleteDenialByAssetId(index, repoConfig, user, assetId) {
    if (!repoConfig?.workspace_wide)
        return null;
    if (!user)
        return null;
    const owner = isWorkspaceOwner(user.role);
    if (!index)
        return owner ? null : DENIAL;
    return index.canDelete(assetId, user.id, owner) ? null : DENIAL;
}
//# sourceMappingURL=asset-delete-authz.js.map