// import axios from 'axios';

// Updated 2024-05-23
export const patch_object = async function patch_object({
	api_cfg = null,
	endpoint = '',
	params = {},
	data = {},
	return_meta = false,
	log_lvl = 0,
	retry_count = 5 // Number of retry attempts
}: {
	api_cfg: any;
	endpoint: string;
	params?: any;
	data?: any;
	return_meta?: boolean;
	log_lvl?: number;
	retry_count?: number;
}) {
	if (log_lvl) {
		console.log(`*** patch_object() *** Endpoint: ${endpoint}`);
		console.log('Params:', params);
		if (log_lvl > 1) {
			console.log('Data:', data);
		}
	}

	if (!api_cfg) {
		console.error('No API Config was provided. Returning false.');
		return false;
	}

	// Construct the URL with query parameters
	const url = new URL(endpoint, api_cfg['base_url']);
	Object.keys(params).forEach((key) => url.searchParams.append(key, params[key]));

	// Clean the headers
	const headers_cleaned: Record<string, string> = {};
	for (const prop in api_cfg['headers']) {
		const prop_cleaned = prop.replaceAll('_', '-');
		headers_cleaned[prop_cleaned] = api_cfg['headers'][prop];
	}

	if (log_lvl > 1) {
		console.log('Cleaned Headers:', headers_cleaned);
	}

	const fetchOptions: RequestInit = {
		method: 'PATCH',
		headers: {
			...headers_cleaned,
			'Content-Type': 'application/json'
		},
		body: JSON.stringify(data)
	};

	if (log_lvl > 1) {
		console.log('Fetch Options:', fetchOptions);
	}

	for (let attempt = 1; attempt <= retry_count; attempt++) {
		try {
			const response = await fetch(url.toString(), fetchOptions);

			if (log_lvl) {
				console.log(`Response: status=${response.status} attempt=${attempt}`);
			}

			if (!response.ok) {
				if (response.status === 404) {
					console.warn('404 Not Found. Returning null.');
					return null; // Returning null since there were no results
				}
				throw new Error(`HTTP error! status: ${response.status}`);
			}

			const json = await response.json();

			if (log_lvl > 1) {
				console.log('Response JSON:', json);
			}

			// Return the response data or metadata
			return return_meta ? json : json.data;
		} catch (error) {
			console.error(`API PATCH error on attempt ${attempt}:`, error);

			// If this is the last attempt, return false
			if (attempt === retry_count) {
				console.error('Max retry attempts reached. Returning false.');
				return false;
			}

			// Log retry information
			if (log_lvl) {
				console.log(`Retrying... (${attempt}/${retry_count})`);
			}
		}
	}

	// let axios_api = axios.create({
	//     baseURL: api_cfg['base_url'],
	//     /* other custom settings */
	// });
	// axios_api.defaults.headers = api_cfg['headers'];

	// for (let attempt = 1; attempt <= retry_count; attempt++) {
	//     try {
	//         const response = await axios_api.patch(endpoint, data, { params: params });
	//         if (log_lvl) {
	//             console.log(`Response: status=${response.status} attempt=${attempt}`);
	//         }
	//         if (log_lvl > 1) {
	//             console.log('Response Data:', response.data);
	//         }

	//         // Return the response data
	//         return response.data['data'];
	//     } catch (error) {
	//         if (log_lvl) {
	//             console.error(`Error on attempt ${attempt}:`, error);
	//         }

	//         // Handle specific errors (e.g., 404)
	//         if (error.response && error.response.status === 404) {
	//             console.warn('404 Not Found. Returning null.');
	//             return null; // Returning null since there were no results
	//         }

	//         // If this is the last attempt, return false
	//         if (attempt === retry_count) {
	//             console.error('Max retry attempts reached. Returning false.');
	//             return false;
	//         }

	//         // Log retry information
	//         if (log_lvl) {
	//             console.log(`Retrying... (${attempt}/${retry_count})`);
	//         }
	//     }
	// }
	// return response_data;
};
