import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import sharp from "sharp";

export const downloadAndGenerateThumbnail = async (url: string) => {
	const image = await fetch(url)
		.then((res) => res.arrayBuffer())
		.then((buffer) => Buffer.from(buffer));
	const thumbnail = await sharp(image).resize(250, 250).jpeg().toBuffer();
	return thumbnail;
};

export const uploadToS3 = async (thumbnail: Buffer, key: string) => {
	try {
		const client = new S3Client({ region: process.env.AWS_REGION });
		await client.send(
			new PutObjectCommand({
				Bucket: process.env.AWS_BUCKET_NAME ?? "",
				Key: key,
				Body: thumbnail,
				ACL: "public-read",
				ContentType: "image/jpeg",
			}),
		);
		return getUploadedFileUrl(key);
	} catch (error) {
		throw new Error(error);
	}
};
export const getUploadedFileUrl = (key: string): string => {
	const bucketName = process.env.AWS_BUCKET_NAME ?? "";
	return `https://${bucketName}.s3.${process.env.AWS_REGION}.amazonaws.com/${key}`;
};
