import axios from "axios";

export default class Thirdparty {
	static async GetData(url: string, field: any, token?: string) {
		try {
			const headers: Record<string, string> = {};
			if (token) {
				headers.Authorization = `Bearer ${token}`;
			}

			const response = await axios.get(url, { params: field, headers });
			const result = response.data;

			if (result.status) {
				return { status: true, message: "Success fetch data", data: result.data };
			} else {
				// Add a default return for falsy result.status
				return { status: false, message: "Unexpected response status", data: null };
			}
		} catch (error: any) {
			const { response } = error;
			return {
				status: false,
				message: response?.data?.error ?? response?.data?.message ?? "Unknown error",
				data: null,
			};
		}
	}

	static async PostData(url: string, field: any, token?: string) {
		try {
			const headers: Record<string, string> = {};
			if (token) {
				headers.Authorization = `Bearer ${token}`;
			}
			const response = await axios.post(url, field, { headers });
			const result = response.data;
			return result;
		} catch (error: any) {
			const { response } = error;
			return { status: false, message: response?.data?.error ?? response?.data?.message ?? "Unknown error" };
		}
	}

	static async UploadFile(url: string, field: any, token?: string) {
		try {
			const headers: Record<string, string> = {};
			if (token) {
				headers.Authorization = `Bearer ${token}`;
			}

			const formData = new FormData();

			// Append the file and other fields to FormData
			for (const key in field) {
				if (field.hasOwnProperty(key)) {
					const value = field[key];

					if (value instanceof Object && value.data && value.mimetype) {
						// Convert file-like object to a Blob
						const blob = new Blob([value.data], { type: value.mimetype });
						formData.append(key, blob, value.name); // Use name as filename
					} else {
						formData.append(key, value); // Append non-file fields
					}
				}
			}

			const response = await axios.post(url, formData, {
				headers: { ...headers, "Content-Type": "multipart/form-data" },
			});

			const result = response.data;

			if (!result.status) throw response;
			return result;
		} catch (error: any) {
			const { response } = error;

			throw {
				status: false,
				message: response?.data?.error ?? response?.data?.message ?? "Unknown error",
				data: null,
			};
		}
	}

	static async DownloadFile(url: string, field: any, token?: string) {
		try {
			const headers: Record<string, string> = {};
			if (token) {
				headers.Authorization = `Bearer ${token}`;
			}

			const response = await axios.get(url, { params: field, headers, responseType: "arraybuffer" });
			const result = response.data;

			return Buffer.from(result);
		} catch (error: any) {
			const { response } = error;
			throw {
				status: false,
				message: response?.data?.error ?? response?.data?.message ?? "Unknown error",
				data: null,
			};
		}
	}
}
