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

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

    // Get media_id before deleting
    const bookmark = db.prepare(`
      SELECT media_id FROM bookmarks WHERE id = ?
    `).get(parsedId) as { media_id: number } | undefined;

    if (!bookmark) {
      return NextResponse.json({ error: 'Bookmark not found' }, { status: 404 });
    }

    // Delete bookmark
    db.prepare(`DELETE FROM bookmarks WHERE id = ?`).run(parsedId);

    // Update media bookmark count
    db.prepare(`
      UPDATE media 
      SET bookmark_count = (SELECT COUNT(*) FROM bookmarks WHERE media_id = ?)
      WHERE id = ?
    `).run(bookmark.media_id, bookmark.media_id);

    return NextResponse.json({ success: true });
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}