import { NextResponse } from 'next/server'
import { checkAdminAuth } from '@/lib/auth-check'
import { minioClient, bucketName, initBucket, getPublicUrl } from '@/lib/minio'

export async function POST(request: Request) {
  const authError = await checkAdminAuth()
  if (authError) return authError

  try {
    const formData = await request.formData()
    const file = formData.get('file') as File

    if (!file) {
      return NextResponse.json({ error: 'No file provided' }, { status: 400 })
    }

    // Validate file type
    const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif']
    if (!validTypes.includes(file.type)) {
      return NextResponse.json({ error: 'Invalid file type. Only images allowed.' }, { status: 400 })
    }

    // Validate file size (max 5MB)
    const maxSize = 5 * 1024 * 1024 // 5MB
    if (file.size > maxSize) {
      return NextResponse.json({ error: 'File too large. Maximum size is 5MB.' }, { status: 400 })
    }

    // Generate unique filename
    const timestamp = Date.now()
    const randomStr = Math.random().toString(36).substring(2, 8)
    const ext = file.name.split('.').pop()
    const fileName = `uploads/${timestamp}-${randomStr}.${ext}`

    // Ensure MinIO bucket exists
    await initBucket()

    // Convert file to buffer
    const bytes = await file.arrayBuffer()
    const buffer = Buffer.from(bytes)

    // Upload to MinIO
    await minioClient.putObject(bucketName, fileName, buffer, buffer.length, {
      'Content-Type': file.type,
    })

    // Return full MinIO public URL
    const url = getPublicUrl(fileName)

    return NextResponse.json({ url }, { status: 201 })
  } catch (error) {
    console.error('Error uploading file:', error)
    return NextResponse.json({ error: 'Failed to upload file' }, { status: 500 })
  }
}
