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

export async function GET(request: Request) {
  try {
    const bookmarks = db.prepare(`
      SELECT m.*, l.path as library_path
      FROM bookmarks b
      JOIN media m ON b.media_id = m.id
      JOIN libraries l ON m.library_id = l.id
      ORDER BY b.updated_at DESC
    `).all();

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

export async function POST(request: Request) {
  try {
    const { mediaId } = await request.json();

    if (!mediaId) {
      return NextResponse.json({ error: 'mediaId is required' }, { status: 400 });
    }

    // 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 });
  }
}