
import { NextRequest, NextResponse } from 'next/server';
import db from '@/db';

export async function DELETE(request: NextRequest, { params: paramsPromise }: { params: Promise<{ id: string }> }) {
  const params = await paramsPromise;
  const id = parseInt(params.id, 10);
  if (isNaN(id)) {
    return NextResponse.json({ error: 'Invalid ID' }, { status: 400 });
  }

  try {
    // First, delete all media associated with this library
    db.prepare('DELETE FROM media WHERE library_id = ?').run(id);
    
    // Then delete the library itself
    const info = db.prepare('DELETE FROM libraries WHERE id = ?').run(id);
    if (info.changes === 0) {
      return NextResponse.json({ error: 'Library not found' }, { status: 404 });
    }
    return NextResponse.json({ message: 'Library deleted successfully' });
  } catch (error: any) {
    console.error('Error deleting library:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
