Skip to content

50+ open-source generative AI apps you can clone, deploy, and monetize — image generators, video tools, virtual try-ons, AI SaaS templates, and platform integrations. One-click Vercel deploy on every template.

1.5 KB
Raw Blame
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { AIService } from "@/lib/services/ai";

export async function POST(req) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    const { modelFamily, prompt, imagesList, aspectRatio, resolution, quality, googleSearch } = await req.json();

    // Compute the real cost before checking balance
    const cost = AIService.computeCreditCost("image", { modelFamily, resolution, quality });

    // Check credits
    const user = await prisma.user.findUnique({
      where: { id: session.user.id },
      select: { credits: true }
    });

    if (!user || user.credits < cost) {
      return new NextResponse(
        `Insufficient credits. This generation costs ${cost} credits but you only have ${user?.credits ?? 0}.`,
        { status: 400 }
      );
    }

    if (!prompt) {
      return new NextResponse("Missing prompt", { status: 400 });
    }

    const creation = await AIService.generateImage(session.user.id, {
      modelFamily,
      prompt,
      imagesList,
      aspectRatio,
      resolution,
      quality,
      googleSearch
    });

    return NextResponse.json(creation);
  } catch (error) {
    console.error("[GENERATE_IMAGE_ERROR]", error);
    return new NextResponse(error.message || "Internal Error", { status: 500 });
  }
}