import { add } from "date-fns";
import z from "zod";

type UploadResponse =
	| {
			success: true;
			id: string;
	  }
	| {
			success: false;
			error: string;
	  };
// Helper to handle file uploads
async function uploadFile(
	file: File,
	expiresAt: string | undefined,
): Promise<UploadResponse> {
	try {
		const formData = new FormData();
		formData.append("file", file);
		if (expiresAt) {
			formData.append("expires_at", expiresAt);
		}
		formData.append("bucket", "storage");

		const response = await fetch(`/storage-api/upload`, {
			method: "POST",
			body: formData,
		});

		if (response.ok) {
			const res = await response.json();
			const parsed = z
				.object({
					id: z.string(),
				})
				.parse(res);
			const fileID = parsed.id;
			return { success: true, id: fileID };
		}

		return {
			success: false,
			error: `Caricamento fallito con status: ${response.status}`,
		};
	} catch (e) {
		return {
			success: false,
			error: `Errore caricamento file: ${(e as Error).message}`,
		};
	}
}

export const uploadHandler = async ({
	files,
	from_admin,
}: {
	files: File[];
	from_admin: boolean;
}) => {
	const attachments = [];
	const failed: string[] = [];
	const expirationDate = add(new Date(), { days: 60 }).toISOString();
	if (files.length === 0) {
		console.error("No files provided");
		return { attachments: [], error: "No files provided", status: false };
	}

	for (const file of files) {
		const upload = await uploadFile(
			file,
			from_admin ? expirationDate : undefined,
		);
		if (upload.success) {
			attachments.push(upload.id);
		} else {
			console.error(`Error uploading file ${file.name}: ${upload.error}`);
			failed.push(file.name);
		}
	}

	return { attachments, failed, status: true };
};
