// form/nc/nc-work-center/change-data.js
// Handles incremental data updates from the server
import { _ as nc } from '/assets/nc-plugin.js'
const message = nc.message

export function applyIncrementalChanges(state, changeArr) {
	if (!changeArr || typeof changeArr !== 'object') {
		return
	}
	if (!state.data) {
		message.setError(state, 'No data available for incremental update')
	}
	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} from ${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
}

function updateGridData(state, changeArr) {
	if (!state.grid) {
		return
	}
	// Map table names to grid names
	const tableToGridMap = {
		'product_work-schedule': 'work',
		'product_work-actual': 'work_phase_actual',
		'product_material-actual': 'product_material_actual',
		'product_material-estimated': 'product_material',
		'person-employee': 'person',
		attachment: 'document'
	}
	for (const tableName in changeArr) {
		const gridName = tableToGridMap[tableName] || tableName
		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`)
			}
		}
	}
}

export function shouldUseIncrementalUpdate(state) {
	// Use incremental updates if we have a last_modify_id and it's not a forced reload
	return state.rec.last_modify_id && Object.keys(state.rec.last_modify_id).length > 0 && state.rec.reload_data !== true
}

export function initializeIncrementalUpdate(state) {
	// Initialize last_modify_id if not present
	if (!state.rec.last_modify_id) {
		state.rec.last_modify_id = {}
	}
}

export function handleIncrementalResponse(state, response) {
	if (!response) {
		return false
	}
	// Check if this is an incremental response
	if (response.incremental === true) {
		if (response.change_arr && Object.keys(response.change_arr).length > 0) {
			// Apply incremental changeArr
			const changeCount = applyIncrementalChanges(state, response.change_arr)
			message.setInfo(state, `Processed incremental update with ${changeCount} changes`)
		} else {
			console.debug('Incremental update with no changes')
		}
		// Update last_modify_id
		if (response.rec && response.rec.last_modify_id) {
			state.rec.last_modify_id = response.rec.last_modify_id
		}
		return true // Indicates this was an incremental update
	}
	// This is a full data response
	if (response.data) {
		// Update state.data with full data
		state.data = response.data
		// Update last_modify_id
		if (response.rec && response.rec.last_modify_id) {
			state.rec.last_modify_id = response.rec.last_modify_id
		}
		console.debug('Processed full data update')
	}
	return false // Indicates this was a full update
}

export function resetIncrementalUpdate(state) {
	// Reset last_modify_id to force a full reload
	state.rec.last_modify_id = {}
	state.rec.reload_data = true
}
