/**
 * cPanel/Plesk-parity protected system path policy (front-end).
 *
 * These paths must NEVER be deleted, moved, or renamed through the customer
 * file manager UI. Their contents may still be opened / created / replaced
 * inside (e.g. dropping `authorized_keys` into `.ssh/`), but the parent
 * directory itself is locked because:
 *
 *  - dotfiles such as `.bashrc` boot the shell — corruption locks the user
 *    out of SSH.
 *  - `.cpanel`, `.htpasswds`, `.onoxsoft`, `.subaccounts` etc. carry panel
 *    state, deleting them silently breaks the dashboard.
 *  - `mail/`, `etc/`, `logs/`, `ssl/`, `tmp/` are panel-managed (the real
 *    files inside are root-owned anyway, so the kernel rejects rm — but we
 *    fail fast in the UI to spare the user a confusing error).
 *
 * This is a **defence-in-depth** layer; FileManager.php enforces the same
 * list on the backend. UI relies on it to grey out actions, but production
 * safety lives in PHP.
 *
 * @see app/Domain/Files/Services/FileManager.php::PROTECTED_RELATIVE_PATHS
 */

/** Top-level directories or dotfiles that may not be removed/moved/renamed. */
const PROTECTED_PATHS = [
    // Linux user dotfiles
    '.bash_profile', '.bashrc', '.bash_logout', '.profile',

    // Onoxsoft / panel state
    '.onoxsoft',

    // cPanel-style protected dirs
    '.cpanel', '.htpasswds', '.subaccounts', '.caldav', '.spamassassin',
    '.razor', '.koality', '.softaculous', '.cagefs',

    // SSH (security — wrong delete locks out remote access)
    '.ssh',

    // Mail Maildir (deleting from panel destroys mail — use Email accounts UI)
    'mail',

    // Backup state (panel-managed)
    'wordpress-backups',

    // ROOT-OWNED or panel-managed
    'etc',  // /home/<user>/etc — readonly
    'logs', // /home/<user>/logs — Apache logs
    'ssl',  // /home/<user>/ssl — cert symlinks
    'tmp',  // /home/<user>/tmp — sticky bit
]

/** Regex patterns flagged as critical (still blocked by default). */
const PROTECTED_FILES_REGEX = [
    /^\.htaccess$/i,    // .htaccess — site routing
    /^\.well-known$/i,  // Let's Encrypt ACME challenge dir
    /^cgi-bin$/i,       // CGI exec dir
    /^php\.ini$/i,      // per-user PHP override
]

/**
 * Inspect a file/folder under a given parent path.
 *
 * @param {string} parentPath - directory containing the item (relative to home, no leading slash)
 * @param {string} name       - leaf name (e.g. ".ssh" or "index.php")
 * @returns {{ protected: boolean, level?: 'system'|'critical', reason?: string }}
 */
export function isProtectedPath(parentPath, name) {
    if (!name) return { protected: false }

    const segments = (parentPath || '').split('/').filter(Boolean)

    // Top-level (parent == home) protected dir / dotfile?
    if (segments.length === 0) {
        if (PROTECTED_PATHS.includes(name)) {
            return {
                protected: true,
                level: 'system',
                reason: `'${name}' sistem klasörü — silmek/taşımak yerine ilgili yönetim sayfasını kullanın.`,
            }
        }
        for (const rx of PROTECTED_FILES_REGEX) {
            if (rx.test(name)) {
                return {
                    protected: true,
                    level: 'critical',
                    reason: `'${name}' kritik — silinmesi site/güvenlik etkiler.`,
                }
            }
        }
    }

    return { protected: false }
}

/**
 * Convenience: pass the row object (`{ name, path, type }`) and the current
 * directory context separately. The current path is what the file manager is
 * currently viewing — the item's name is the leaf inside it.
 */
export function isProtectedItem(item, currentPath = '') {
    if (!item) return { protected: false }
    return isProtectedPath(currentPath, item.name)
}

export function canDelete(item, currentPath = '') {
    return !isProtectedItem(item, currentPath).protected
}

export function canMove(item, currentPath = '') {
    return !isProtectedItem(item, currentPath).protected
}

export function canRename(item, currentPath = '') {
    return !isProtectedItem(item, currentPath).protected
}

/**
 * Composable wrapper — gives Vue components a single import that pre-binds
 * the current path so call-sites stay terse.
 *
 *   const { isProtected, canDelete } = useFileProtection(() => props.path)
 *   v-if="!canDelete(item)"   // hides the trash icon for .ssh, etc.
 */
export function useFileProtection(currentPathRef) {
    const resolve = () => (typeof currentPathRef === 'function'
        ? currentPathRef()
        : (currentPathRef?.value ?? currentPathRef ?? ''))

    return {
        isProtected: (item) => isProtectedItem(item, resolve()),
        canDelete: (item) => canDelete(item, resolve()),
        canMove: (item) => canMove(item, resolve()),
        canRename: (item) => canRename(item, resolve()),
        // Pass-throughs for callers that already have an explicit parent.
        isProtectedPath,
        isProtectedItem,
    }
}
