// form/nc/lib/change-data.js
// Shared incremental data update handler for all forms
import { _ as nc } from '/assets/nc-plugin.js'
const message = nc.message

function updateGridData(state, changeArr) {
	if (!state.grid) {
		return
	}
	for (const tableName in changeArr) {
		const gridName = tableName.replaceAll('-', '_')
		if (state.grid[gridName] && state.grid[gridName].data) {
			// Update grid data to match state.data
			if (state.data[tableName]) {
				state.grid[gridName].data = [...state.data[tableName]]
				message.setInfo(state, `Updated grid ${gridName} with ${state.data[tableName].length} records`)
			}
		}
	}
}

function applyChangeArr(state, changeArr) {
	if (!changeArr || typeof changeArr !== 'object') {
		return 0
	}
	if (!state.data) {
		message.setError(state, 'No data available for incremental update')
		return 0
	}
	let totalChanges = 0
	// Process each table's changeArr
	for (const tableName in changeArr) {
		const tableChangeArr = changeArr[tableName]
		if (!Array.isArray(tableChangeArr)) {
			continue
		}
		// Ensure the table exists in state.data
		if (!state.data[tableName]) {
			state.data[tableName] = []
		}
		const dataArray = state.data[tableName]
		// Process each change in the table
		for (const changeRecord of tableChangeArr) {
			const recordId = changeRecord.record_id
			const changeType = changeRecord.__change
			if (!recordId) {
				message.setWarning(state, 'Change record missing record_id:', changeRecord)
				continue
			}
			// Find existing record index
			const existingIndex = dataArray.findIndex(item => item.record_id === recordId)
			switch (changeType) {
				case 'new':
					// Add new record
					delete changeRecord.__change
					if (existingIndex >= 0) {
						// Record already exists, replace it
						dataArray[existingIndex] = changeRecord
						message.setInfo(state, `Updated existing record ${recordId} in ${tableName}`)
					} else {
						// Truly new record
						dataArray.push(changeRecord)
						message.setInfo(state, `Added new record ${recordId} to ${tableName}`)
					}
					totalChanges++
					break
				case 'change':
					// Update existing record
					if (existingIndex >= 0) {
						delete changeRecord.__change
						dataArray[existingIndex] = changeRecord
						message.setInfo(state, `Updated record ${recordId} in ${tableName}`)
						totalChanges++
					} else {
						message.setWarning(state, `Attempted to update non-existent record ${recordId} in ${tableName}`)
					}
					break
				case 'delete':
					// Remove record
					if (existingIndex >= 0) {
						dataArray.splice(existingIndex, 1)
						message.setInfo(state, `Deleted record ${recordId} from ${tableName}`)
						totalChanges++
					} else {
						message.setWarning(state, `Attempted to delete non-existent record ${recordId} in ${tableName}`)
					}
					break
				default:
					message.setWarning(state, `Unknown change type '${changeType}' for record ${recordId} in ${tableName}`)
			}
		}
	}
	// Update grid data if grids exist
	updateGridData(state, changeArr)
	message.setInfo(state, `Applied ${totalChanges} incremental changes`)
	return totalChanges
}

// Single function for all incremental update operations
// incrementalUpdate(state) - initialize last_modify_id
// incrementalUpdate(state, response) - process server response (change_arr determines incremental)
// incrementalUpdate(state, null, 'reset') - reset to force full reload
// incrementalUpdate(state, changeArr, 'apply') - apply changes directly
export function incrementalUpdate(state, param, option) {
	// Reset mode: force full reload
	if (option === 'reset') {
		state.rec.last_modify_id = {}
		state.rec.reload_data = true
		return
	}
	// Apply mode: apply changeArr directly
	if (option === 'apply') {
		return applyChangeArr(state, param)
	}
	// Initialize mode: ensure last_modify_id exists
	if (param === undefined) {
		if (!state.rec.last_modify_id) {
			state.rec.last_modify_id = {}
		}
		return
	}
	// Process response mode (param is response)
	if (!param) {
		return
	}
	const response = param
	// Check if response has change_arr (incremental) or grid/data (full)
	const wasIncremental = response.change_arr
	if (wasIncremental && Object.keys(response.change_arr).length > 0) {
		// Incremental update with changes
		const changeCount = applyChangeArr(state, response.change_arr)
		message.setInfo(state, `Processed incremental update with ${changeCount} changes`)
	} else if (wasIncremental) {
		// Incremental update with no changes
		console.debug('Incremental update with no changes')
	} else if (response.grid) {
		// Full data update (grid format) - assign all grids generically
		for (const gridName in response.grid) {
			state.grid[gridName] = response.grid[gridName]
		}
		console.debug('Processed full grid data update')
	} else if (response.data) {
		// Full data update (data format) - used by work-center
		state.data = response.data
		console.debug('Processed full data update')
	}
	// Always update last_modify_id if present
	if (response.rec && response.rec.last_modify_id) {
		state.rec.last_modify_id = response.rec.last_modify_id
	}
	return wasIncremental
}
