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') || 'created_at';
  const sortOrder = searchParams.get('sortOrder') || 'DESC';

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

  let whereClause = "WHERE m.type = 'photo'";
  let params: any[] = [];

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

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

  // Get paginated results
  const query = `
    SELECT 
      m.*,
      COALESCE(b.bookmark_count, 0) as bookmark_count,
      COALESCE(s.avg_rating, 0) as avg_rating,
      COALESCE(s.star_count, 0) as star_count
    FROM media m
    LEFT JOIN (
      SELECT media_id, COUNT(*) as bookmark_count 
      FROM bookmarks 
      GROUP BY media_id
    ) b ON m.id = b.media_id
    LEFT JOIN (
      SELECT 
        media_id, 
        AVG(rating) as avg_rating,
        COUNT(*) as star_count
      FROM stars 
      GROUP BY media_id
    ) s ON m.id = s.media_id
    ${whereClause}
    ORDER BY m.${sortColumn} ${sortDirection}
    LIMIT ? OFFSET ?
  `;

  const photos = db.prepare(query).all(...params, limit, offset);

  return NextResponse.json({
    photos,
    pagination: {
      total,
      limit,
      offset,
      hasMore: offset + limit < total
    }
  });
}