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

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

    // Check if media exists
    const media = db.prepare(`
      SELECT id FROM media WHERE id = ?
    `).get(mediaId) as { id: number } | undefined;

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

    // Check if already bookmarked
    const existing = db.prepare(`
      SELECT id FROM bookmarks WHERE media_id = ?
    `).get(mediaId);

    if (existing) {
      return NextResponse.json({ error: 'Already bookmarked' }, { status: 400 });
    }

    // Insert bookmark
    const result = db.prepare(`
      INSERT INTO bookmarks (media_id) VALUES (?)
    `).run(mediaId);

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

    return NextResponse.json({ id: result.lastInsertRowid });
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

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

    // Check if bookmark exists
    const bookmark = db.prepare(`
      SELECT id FROM bookmarks WHERE media_id = ?
    `).get(mediaId) as { id: number } | undefined;

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

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

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

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