import { PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { v4 as uuidv4 } from "uuid";
import { s3Client, S3_BUCKET, getPublicUrl } from "./s3";

const MAX_FILE_SIZE = 5 * 1024 * 1024;
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"];
const MAX_FILES = 3;

export { MAX_FILE_SIZE, ALLOWED_TYPES, MAX_FILES, getPublicUrl };

export async function generatePresignedUrl(
  contentType: string,
  userId: string
): Promise<{ url: string; key: string; publicUrl: string }> {
  if (!ALLOWED_TYPES.includes(contentType)) {
    throw new Error(`Invalid content type: ${contentType}`);
  }

  const ext = contentType.split("/")[1];
  const key = `uploads/${userId}/${uuidv4()}.${ext}`;

  const command = new PutObjectCommand({
    Bucket: S3_BUCKET,
    Key: key,
    ContentType: contentType,
  });

  const url = await getSignedUrl(s3Client, command, { expiresIn: 3600 });

  return {
    url,
    key,
    publicUrl: getPublicUrl(key),
  };
}