import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs'
import { cookies } from 'next/headers'
import { NextRequest, NextResponse } from 'next/server'
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

const s3Client = new S3Client({
  region: process.env.AWS_REGION || 'eu-west-3',
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID || '',
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || '',
  },
})

export async function GET(request: NextRequest) {
  try {
    const supabase = createRouteHandlerClient({ cookies })
    
    // Vérifier l'authentification
    const { data: { session } } = await supabase.auth.getSession()
    if (!session) {
      console.error('📥 Download API - No session')
      return new NextResponse('Unauthorized', { status: 401 })
    }

    const searchParams = request.nextUrl.searchParams
    const path = searchParams.get('path')
    
    console.log('📥 Download API - Request for path:', path)
    
    if (!path) {
      console.error('📥 Download API - Missing path parameter')
      return new NextResponse('Missing path parameter', { status: 400 })
    }

    // Télécharger le fichier depuis S3
    const bucketName = process.env.AWS_S3_BUCKET_NAME || "odentas-docs"
    const command = new GetObjectCommand({
      Bucket: bucketName,
      Key: path,
    })

    console.log('📥 Download API - Fetching from S3, bucket:', bucketName, 'key:', path)

    const response = await s3Client.send(command)
    
    if (!response.Body) {
      console.error('📥 Download API - File not found in S3')
      return new NextResponse('File not found', { status: 404 })
    }

    // Convertir le stream en buffer
    const chunks: Uint8Array[] = []
    for await (const chunk of response.Body as any) {
      chunks.push(chunk)
    }
    const buffer = Buffer.concat(chunks)

    console.log('📥 Download API - File downloaded, size:', buffer.length, 'bytes')

    // Extraire le nom du fichier depuis le path
    const filename = path.split('/').pop() || 'document.txt'

    console.log('📥 Download API - Sending file:', filename)

    // Retourner le fichier avec les bons headers pour forcer le téléchargement
    return new NextResponse(buffer, {
      headers: {
        'Content-Type': 'text/plain; charset=utf-8',
        'Content-Disposition': `attachment; filename="${filename}"`,
      },
    })
  } catch (error) {
    console.error('📥 Download API - Error:', error)
    return new NextResponse('Internal Server Error', { status: 500 })
  }
}
