import * as Minio from 'minio'

const minioClient = new Minio.Client({
  endPoint: process.env.MINIO_ENDPOINT || 'localhost',
  port: parseInt(process.env.MINIO_PORT || '9000'),
  useSSL: process.env.MINIO_USE_SSL === 'true',
  accessKey: process.env.MINIO_ACCESS_KEY || 'minioadmin',
  secretKey: process.env.MINIO_SECRET_KEY || 'minioadmin123',
})

const BUCKET = process.env.MINIO_BUCKET || 'lageplan-icons'

export async function ensureBucket(): Promise<void> {
  const exists = await minioClient.bucketExists(BUCKET)
  if (!exists) {
    await minioClient.makeBucket(BUCKET)
  }
}

export async function uploadFile(
  fileKey: string,
  buffer: Buffer,
  mimeType: string
): Promise<string> {
  await ensureBucket()
  await minioClient.putObject(BUCKET, fileKey, buffer, buffer.length, {
    'Content-Type': mimeType,
  })
  return fileKey
}

export async function getFileUrl(fileKey: string): Promise<string> {
  const publicUrl = process.env.MINIO_PUBLIC_URL || 'http://localhost:9000'
  return `${publicUrl}/${BUCKET}/${fileKey}`
}

export async function getFileStream(fileKey: string): Promise<{ stream: NodeJS.ReadableStream; contentType: string }> {
  const stat = await minioClient.statObject(BUCKET, fileKey)
  const stream = await minioClient.getObject(BUCKET, fileKey)
  return { stream, contentType: stat.metaData['content-type'] || 'application/octet-stream' }
}

export async function deleteFile(fileKey: string): Promise<void> {
  await minioClient.removeObject(BUCKET, fileKey)
}

export async function getPresignedUrl(
  fileKey: string,
  expirySeconds: number = 3600
): Promise<string> {
  return await minioClient.presignedGetObject(BUCKET, fileKey, expirySeconds)
}

export { minioClient, BUCKET }
