import { FileType } from "@/contracts/client.schemas";
import { openLink } from "@/shared/link-utils";

const getMimeType = (filename: string): string => {
	const extension = filename.split(".").pop()?.toLowerCase();

	switch (extension) {
		case "pdf":
			return "application/pdf";
		case "xlsx":
			return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
		case "zip":
			return "application/zip";
		default:
			return "application/octet-stream";
	}
};

export const getFileExtension = (fileType: FileType): string => {
	switch (fileType) {
		case FileType.Pdf:
			return ".pdf";
		case FileType.Excel:
			return ".xlsx";
		case FileType.Zip:
			return ".zip";
		default:
			throw new Error("File format not supported");
	}
};

export const saveFile = (data: BlobPart | number[], filename: string): void => {
	const mimeType = getMimeType(filename);
	const blob =
		ArrayBuffer.isView(data) || Array.isArray(data)
			? new Blob([new Uint8Array(data as number[])], { type: mimeType })
			: new Blob([data], { type: mimeType });

	// Создаем URL для blob
	const url = URL.createObjectURL(blob);

	openLink(url, filename);
};
