///////////////////////////////////////////////////////////////////////////////
// portfolio-editable.js
// Reads PORTFOLIO_EDITABLE_FIELDS (emitted by portfolio.php) and applies
// inline edit metadata to the matching column definitions.
//
// Public API:
//   applyEditableFields(colDefs, domainColumns) -> colDefs (mutated in place)
//
// Called from portfolio.js after buildColumnDefsFromDomainColumns, and from
// columns.js after the column picker applies a new column set.
///////////////////////////////////////////////////////////////////////////////

/**
 * Marks matching columns in colDefs as editable based on PORTFOLIO_EDITABLE_FIELDS.
 * Silently skips fields that are not in domainColumns or not in the current
 * column set — editing is simply unavailable for those columns.
 *
 * @param {Array}  colDefs       - Column defs from buildColumnDefsFromDomainColumns
 * @param {Object} domainColumns - Column metadata from the API (keyed by bare name)
 * @returns {Array} The same colDefs array, mutated in place
 */
function applyEditableFields(colDefs, domainColumns) {
	// Respect user edit rights — don't mark columns editable for non-edit users
    if (typeof user_details !== 'undefined' && user_details.rights !== 65535) {
        if (!bit_test(user_details.rights, ALLOW_EDIT_BITPOS)) return colDefs;
    }
	
    const fields = window.PORTFOLIO_EDITABLE_FIELDS;

    if (!Array.isArray(fields) || fields.length === 0) return colDefs;
    if (!colDefs || !domainColumns)                    return colDefs;

    fields.forEach(function(entry) {
        const field = entry.field;

        // Validate field exists in domainColumns API metadata
        if (!(field in domainColumns)) {
            console.warn('[editable] Field not found in domain columns, skipping:', field);
            return;
        }

        // Find the matching column def — columns use d. prefix
        const colName = 'd.' + field;
        const col     = colDefs.find(c => c.name === colName);

        if (!col) {
            // Column not in current visible set — silently skip
            return;
        }

        col.editable  = true;
        col.editField = field;
        col.editType  = entry.type  || 'text';
        col.editLabel = entry.label || field;
    });

    return colDefs;
}