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

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  
  const limit = Math.min(parseInt(searchParams.get('limit') || '50'), 100);
  const offset = parseInt(searchParams.get('offset') || '0');
  const search = searchParams.get('search') || '';
  const sortBy = searchParams.get('sortBy') || 'updated_at';
  const sortOrder = searchParams.get('sortOrder') || 'DESC';

  // Validate sort parameters to prevent SQL injection
  const allowedSortColumns = ['updated_at', 'created_at', 'title', 'size', 'type'];
  const allowedSortOrders = ['ASC', 'DESC'];
  
  const sortColumn = allowedSortColumns.includes(sortBy) ? sortBy : 'updated_at';
  const sortDirection = allowedSortOrders.includes(sortOrder.toUpperCase()) ? sortOrder.toUpperCase() : 'DESC';

  let whereClause = '';
  let params: any[] = [];

  if (search) {
    whereClause = "WHERE (m.title LIKE ? OR m.path LIKE ?)";
    params.push(`%${search}%`, `%${search}%`);
  }

  try {
    // Get total count for pagination
    const countQuery = `
      SELECT COUNT(*) as total
      FROM bookmarks b
      JOIN media m ON b.media_id = m.id
      ${whereClause}
    `;
    const totalResult = db.prepare(countQuery).get(...params) as { total: number };
    const total = totalResult.total;

    // Get paginated results
    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
      ${whereClause}
      ORDER BY b.${sortColumn} ${sortDirection}
      LIMIT ? OFFSET ?
    `).all(...params, limit, offset);

    return NextResponse.json({
      bookmarks,
      pagination: {
        total,
        limit,
        offset,
        hasMore: offset + limit < total
      }
    });
  } 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 });
  }
}