/**
 * GET /api/page-studio/free-images?query=X&page=1 — Search copyright-free images.
 * Uses Unsplash (primary) or Pexels (fallback). Optional API keys.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { searchFreeImages } from "@/lib/services/free-image-search";

export const dynamic = "force-dynamic";

// Simple in-memory rate limiter: max 30 requests per minute per user
const rateLimits = new Map<string, { count: number; reset: number }>();
const MAX_PER_MIN = 30;

function rateCheck(userId: string): boolean {
  const now = Date.now();
  const entry = rateLimits.get(userId);
  if (!entry || now > entry.reset) {
    rateLimits.set(userId, { count: 1, reset: now + 60000 });
    return true;
  }
  if (entry.count >= MAX_PER_MIN) return false;
  entry.count++;
  return true;
}

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  if (!rateCheck(user.id)) {
    return NextResponse.json({ error: "Rate limit exceeded" }, { status: 429 });
  }

  const url = new URL(req.url);
  const query = url.searchParams.get("query")?.trim();
  const page = Math.max(1, parseInt(url.searchParams.get("page") || "1", 10));

  if (!query) return NextResponse.json({ error: "query parameter required" }, { status: 400 });

  try {
    const result = await searchFreeImages(query, page);
    return NextResponse.json(result);
  } catch (err) {
    return NextResponse.json(
      { images: [], source: null, message: err instanceof Error ? err.message : "Search failed" },
      { status: 500 },
    );
  }
}
