import { S3Client, PutObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3';

// Backend connects to MinIO via MINIO_ENDPOINT (internal Docker: http://minio:9000).
// Public URLs use MINIO_PUBLIC_URL (browser-accessible: http://localhost:9000).
const ENDPOINT   = process.env.MINIO_ENDPOINT   || 'http://localhost:9000';
const PUBLIC_URL = process.env.MINIO_PUBLIC_URL  || ENDPOINT;
const BUCKET     = process.env.MINIO_BUCKET      || 'glitch-university';

const client = new S3Client({
  endpoint: ENDPOINT,
  region: 'us-east-1',
  credentials: {
    accessKeyId:     process.env.MINIO_ROOT_USER     || 'minioadmin',
    secretAccessKey: process.env.MINIO_ROOT_PASSWORD || 'minioadmin',
  },
  forcePathStyle: true,  // required for MinIO
});

export function publicUrl(objectKey) {
  return `${PUBLIC_URL}/${BUCKET}/${objectKey}`;
}

export async function uploadBuffer(objectKey, buffer, contentType) {
  await client.send(new PutObjectCommand({
    Bucket: BUCKET,
    Key: objectKey,
    Body: buffer,
    ContentType: contentType,
  }));
  return publicUrl(objectKey);
}

export async function deleteObject(objectKey) {
  await client.send(new DeleteObjectCommand({
    Bucket: BUCKET,
    Key: objectKey,
  }));
}
