import { NextRequest, NextResponse } from 'next/server'
import { requireStaffPermission } from '@/lib/auth-helpers'
import { storageService } from '@/lib/services/storage-service'

/**
 * POST /api/v1/admin/settings/storage/test
 * Test S3/MinIO connection
 * Requires: settings:edit permission
 */
export async function POST(request: NextRequest) {
  try {
    await requireStaffPermission('settings:edit')

    // Get optional config override from body
    const body = await request.json().catch(() => ({}))

    // If config is provided in body, test with that config (for testing before saving)
    if (body.endpoint && body.bucket && body.accessKey && body.secretKey) {
      const result = await storageService.testConnection({
        endpoint: body.endpoint,
        bucket: body.bucket,
        accessKey: body.accessKey,
        secretKey: body.secretKey,
        region: body.region || 'us-east-1',
        useSsl: body.useSsl !== false,
      })

      return NextResponse.json(result)
    }

    // Otherwise test with stored settings
    const result = await storageService.testConnection()
    return NextResponse.json(result)
  } catch (error) {
    if (typeof error === 'object' && error !== null && 'status' in error) {
      const err = error as { status: number; message: string }
      return NextResponse.json({ error: err.message }, { status: err.status })
    }
    console.error('Error testing storage connection:', error)
    return NextResponse.json(
      { success: false, message: 'Failed to test storage connection' },
      { status: 500 }
    )
  }
}
