import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { unlink } from 'fs/promises'
import path from 'path'

// DELETE /api/fichiers/[id] - Delete a file
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    // Get file info
    const fichier = await db.fichier.findUnique({
      where: { id: id },
    })

    if (!fichier) {
      return NextResponse.json(
        { error: 'File not found' },
        { status: 404 }
      )
    }

    // Delete from database
    await db.fichier.delete({
      where: { id: id },
    })

    // Try to delete the file from disk
    try {
      const filePath = path.join(process.cwd(), 'public', fichier.url)
      await unlink(filePath)
    } catch (error) {
      // File might not exist, but that's okay
      console.warn('File not found on disk:', fichier.url)
    }

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting fichier:', error)
    return NextResponse.json(
      { error: 'Failed to delete file' },
      { status: 500 }
    )
  }
}
