import axios, { AxiosError } from "axios";
import { ProblemDetails } from "./models/Types";

export function CatchError(error: unknown) : Error | undefined{
    if (axios.isAxiosError(error)) {
        console.error('error message: ', error.message);
        const problemDetails = (error as AxiosError)?.response?.data as ProblemDetails;
        if (problemDetails?.title) throw new Error(problemDetails.title);
    }
    console.error('unexpected error: ', error);
    // return [];
    //return 'An unexpected error occurred';
    throw new Error(`unexpected error: ${(error as Error)?.message ?? JSON.stringify(error, null, 4)}`);
}

export function AppendFormData(formData: FormData, key: string, value: unknown) {
	const isFile = value instanceof File;
	if (value !== undefined && value !== null) {
		if (Array.isArray(value)) {
			value.forEach((item, index) => {
			AppendFormData(formData, `${key}[${index}]`, item);
			});
		}
		else if (value instanceof Date) {
			formData.append(key, value.toISOString());
		}
		else if (typeof value === 'object' && !isFile) {
			Object.entries(value).forEach(([subKey, subValue]) => {
				if (value != null) {
					AppendFormData(formData, `${key}.${subKey}`, subValue);
				}
			});
		}
		else {
			if (!isFile){
				formData.append(key, value.toString());
			} else{
				formData.append(key, value);
			}
		}
	}
}