import type { ColumnFormat, Row } from './types'

export function flattenObject(obj: Row, prefix = ''): Row {
	const flattened: Row = {}
	for (const key in obj) {
		if (!Object.hasOwn(obj, key)) { continue }
		const value = obj[key]
		const newKey = prefix ? `${prefix}.${key}` : key
		if (value && typeof value === 'object' && !Array.isArray(value)) {
			Object.assign(flattened, flattenObject(value, newKey))
		} else {
			flattened[newKey] = value
		}
	}
	return flattened
}

export function unflattenObject(obj: Row): Row {
	const result: Row = {}
	for (const key in obj) {
		if (!Object.hasOwn(obj, key)) { continue }
		const keys = key.split('.')
		let current = result
		for (let i = 0; i < keys.length - 1; i++) {
			const k = keys[i]
			if (!current[k]) { current[k] = {} }
			current = current[k]
		}
		current[keys[keys.length - 1]] = obj[key]
	}
	return result
}

export function formatCellValue(value: any, format?: ColumnFormat): string {
	if (value === null || value === undefined) { return '' }
	switch (format) {
		case 'image':
			return String(value)
		case 'boolean':
			return ''
		case 'number':
			return Number(value).toLocaleString()
		case 'currency':
			return Number(value).toLocaleString(undefined, { style: 'currency', currency: 'USD' })
		case 'date':
			return value ? new Date(value).toLocaleDateString() : ''
		case 'percentage':
			return Number(value).toLocaleString(undefined, { style: 'percent', minimumFractionDigits: 2 })
		default:
			return String(value)
	}
}

export function parseValueForFormat(value: string | boolean, format?: ColumnFormat): any {
	switch (format) {
		case 'boolean':
			return typeof value === 'boolean' ? value : value === 'true'
		case 'number':
		case 'percentage':
		case 'currency':
			if (typeof value === 'boolean') { return null }
			return value === '' ? null : Number(String(value).replace(/[^0-9.-]/g, ''))
		case 'date':
			if (typeof value === 'boolean') { return null }
			return value === '' ? null : new Date(String(value)).toISOString()
		default:
			return String(value)
	}
}
