// src/utils/s3.ts
import S3 from "aws-sdk/clients/s3";



// Condig to setup a s3 instance
type S3Config = {
  region?: string;
  accessKeyId?: string;
  secretAccessKey?: string;
  signatureVersion?: string;
};

export function createS3Client(config?: S3Config) {
  return new S3({
    region: config?.region ?? process.env.PRESIGN_AWS_REGION,
    accessKeyId: config?.accessKeyId ?? process.env.PRESIGN_AWS_ACCESS_KEY,
    secretAccessKey: config?.secretAccessKey ?? process.env.PRESIGN_AWS_SECRET_KEY,
    signatureVersion: config?.signatureVersion ?? "v4",
  });
}


//  Get presigned url from s3
export type PresignGetOptions = {
  bucket: string;
  key: string;
  expiresInSeconds?: number;         // default 300
  ContentType?: string;
};

/** Presign a GET URL using an existing S3 instance (aws-sdk v2). */
export async function presignGetUrl(
  s3: S3,
  { bucket, key, expiresInSeconds = 300, ContentType}: PresignGetOptions
): Promise<string> {
  return (s3 as any).getSignedUrlPromise("putObject", {
    Bucket: bucket,
    Key: key,
    Expires: expiresInSeconds,
    ContentType: ContentType,
  });
}

export async function uploadFileToS3({
  presignedUrl,
  file,
  contentType,
}: {
  presignedUrl: string;
  file: Blob;
  contentType: string;
}) {
  try {
    const response = await fetch(presignedUrl, {
      method: "PUT",
      body: file,
      headers: { "Content-Type": contentType },
    });

    if (!response.ok) {
      const body = await response.text().catch(() => "(unreadable)");
      console.error("Upload failed", { status: response.status, statusText: response.statusText, body });
      throw new Error(`Upload failed: ${response.status} ${response.statusText}`);
    }
  } catch (error) {
    console.error("Upload error:", error);
    throw new Error("Upload failed.");
  }

  console.log("File uploaded successfully");
  return { success: true };
}