import { toRFC3339 } from './helpers';

/**
 * Converts FormData to a nested object structure
 * @param {FormData} formData - The FormData object to convert
 * @returns {{ object: Partial<App.Locals['user']> | Partial<App.Types['subscription']>, password2: string }} Nested object representation of the form data
 */
export function formDataToObject(formData) {
	/** @type { Partial<App.Locals['user']> | Partial<App.Types['subscription']> } */
	const object = {};
	let password2 = '';

	console.log('Form data entries:');
	for (const [key, value] of formData.entries()) {
		console.log('Key:', key, 'Value:', value);
		if (key == 'password2') {
			password2 = String(value);
			continue;
		}
		/** @type {string[]} */
		const keys = key.match(/\[([^\]]+)\]/g)?.map((k) => k.slice(1, -1)) || [key];
		console.log('Processed keys:', keys);
		console.dir(value);
		/** @type {Record<string, any>} */
		let current = object;

		// console.log('Current object state:', JSON.stringify(current));
		for (let i = 0; i < keys.length - 1; i++) {
			/**
			 * Create nested object if it doesn't exist
			 * @type {Record<string, any>}
			 * @description Ensures proper nesting structure for user data fields
			 * @example
			 * // For input name="user[membership][status]"
			 * // Creates: { user: { membership: { status: value } } }
			 */
			current[keys[i]] = current[keys[i]] || {};
			/**
			 * Move to the next level of the object
			 * @type {Record<string, any>}
			 */
			current = current[keys[i]];
		}

		const lastKey = keys[keys.length - 1];
		if (key.endsWith('[]')) {
			current[lastKey] = current[lastKey] || [];
			try {
				/** @type {{id: number, category: string}} */
				current[lastKey].push(JSON.parse(value.toString()));
			} catch {
				current[lastKey].push(value);
			}
		} else {
			current[lastKey] = value;
		}
	}

	return { object: object, password2: password2 };
}

/**
 * Processes the raw form data into the expected user data structure
 * @param {{  object: Partial<App.Locals['user']>, password2: string} } rawData - The raw form data object
 * @returns {{ user: Partial<App.Locals['user']> }} Processed user data
 */
export function processUserFormData(rawData) {
	/** @type {{ user: Partial<App.Locals['user']> }} */
	let processedData = {
		user: {
			id: Number(rawData.object.id) || 0,
			status: Number(rawData.object.status),
			role_id: Number(rawData.object.role_id),
			first_name: String(rawData.object.first_name),
			last_name: String(rawData.object.last_name),
			email: String(rawData.object.email),
			phone: String(rawData.object.phone || ''),
			company: String(rawData.object.company || ''),
			dateofbirth: toRFC3339(String(rawData.object.dateofbirth || '')),
			address: String(rawData.object.address || ''),
			zip_code: String(rawData.object.zip_code || ''),
			city: String(rawData.object.city || ''),
			notes: String(rawData.object.notes || ''),
			profile_picture: String(rawData.object.profile_picture || ''),

			membership: {
				id: Number(rawData.object.membership?.id) || 0,
				status: Number(rawData.object.membership?.status),
				start_date: toRFC3339(String(rawData.object.membership?.start_date || '')),
				end_date: toRFC3339(String(rawData.object.membership?.end_date || '')),
				parent_member_id: Number(rawData.object.membership?.parent_member_id) || 0,
				subscription_model: {
					id: Number(rawData.object.membership?.subscription_model?.id) || 0,
					name: String(rawData.object.membership?.subscription_model?.name) || '',
					details: String(rawData.object.membership?.subscription_model?.details) || '',
					conditions: String(rawData.object.membership?.subscription_model?.conditions) || '',
					hourly_rate: Number(rawData.object.membership?.subscription_model?.hourly_rate) || 0,
					monthly_fee: Number(rawData.object.membership?.subscription_model?.monthly_fee) || 0,
					included_hours_per_month:
						Number(rawData.object.membership?.subscription_model?.included_hours_per_month) || 0,
					included_hours_per_year:
						Number(rawData.object.membership?.subscription_model?.included_hours_per_year) || 0
				}
			},

			licence: {
				id: Number(rawData.object.licence?.id) || 0,
				status: Number(rawData.object.licence?.status),
				number: String(rawData.object.licence?.number || ''),
				issued_date: toRFC3339(String(rawData.object.licence?.issued_date || '')),
				expiration_date: toRFC3339(String(rawData.object.licence?.expiration_date || '')),
				country: String(rawData.object.licence?.country || ''),
				categories: rawData.object.licence?.categories || []
			},

			bank_account: {
				id: Number(rawData.object.bank_account?.id) || 0,
				account_holder_name: String(rawData.object.bank_account?.account_holder_name || ''),
				bank: String(rawData.object.bank_account?.bank || ''),
				iban: String(rawData.object.bank_account?.iban || ''),
				bic: String(rawData.object.bank_account?.bic || ''),
				mandate_reference: String(rawData.object.bank_account?.mandate_reference || ''),
				mandate_date_signed: toRFC3339(
					String(rawData.object.bank_account?.mandate_date_signed || '')
				)
			}
		}
	};
	console.log('Categories: --------');
	console.dir(rawData.object.licence);
	if (
		rawData.object.password &&
		rawData.password2 &&
		rawData.object.password === rawData.password2 &&
		rawData.object.password.trim() !== ''
	) {
		processedData.user.password = rawData.object.password;
	}
	const clean = JSON.parse(JSON.stringify(processedData), (key, value) =>
		value !== null && value !== '' ? value : undefined
	);
	console.dir(clean);
	return clean;
}

/**
 * Processes the raw form data into the expected user data structure
 * @param {{  object: Partial<App.Types['subscription']>} } rawData - The raw form data object
 * @returns {{ subscription: Partial<App.Types['subscription']> }} Processed user data
 */
export function processSubscriptionFormData(rawData) {
	/** @type {{ subscription: Partial<App.Types['subscription']> }} */
	let processedData = {
		subscription: {
			id: Number(rawData.object.id) || 0,
			name: String(rawData.object.name) || '',
			details: String(rawData.object.details) || '',
			conditions: String(rawData.object.conditions) || '',
			hourly_rate: Number(rawData.object.hourly_rate) || 0,
			monthly_fee: Number(rawData.object.monthly_fee) || 0,
			included_hours_per_month: Number(rawData.object.included_hours_per_month) || 0,
			included_hours_per_year: Number(rawData.object.included_hours_per_year) || 0
		}
	};
	const clean = JSON.parse(JSON.stringify(processedData), (key, value) =>
		value !== null && value !== '' ? value : undefined
	);
	console.dir(clean);
	return clean;
}
