"use node";

import { action } from "./_generated/server";
import { v } from "convex/values";

// Search GIFs via Tenor API
export const search = action({
  args: {
    q: v.string(),
    limit: v.optional(v.number()),
  },
  returns: v.any(),
  handler: async (_ctx, args) => {
    const apiKey = process.env.TENOR_API_KEY;

    if (!apiKey) {
      console.warn("TENOR_API_KEY missing");
      return { results: [] };
    }

    const limit = args.limit || 8;
    const url = `https://tenor.googleapis.com/v2/search?q=${encodeURIComponent(args.q)}&key=${apiKey}&limit=${limit}`;

    const response = await fetch(url);
    if (!response.ok) {
      console.error("Tenor API Error:", response.statusText);
      return { results: [] };
    }

    return await response.json();
  },
});

// Get GIF categories
export const categories = action({
  args: {},
  returns: v.any(),
  handler: async () => {
    // Return static categories (same as the JSON file in backend)
    // These are loaded from the frontend data file
    return { categories: [] };
  },
});
