File size: 4,693 Bytes
64fa001
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import { auth } from "@/auth"
import { checkAndResetDailyCredits, deductCredits } from "@/lib/credits"
import { prisma } from "@/lib/prisma"
import { NextRequest, NextResponse } from "next/server"

export const DEFAULT_NEGATIVE_PROMPT = "blurry, low quality, bad anatomy, bad hands, distorted, ugly, pixelated, watermark, text, signature, grains, haze"

export async function POST(req: NextRequest) {
    try {
        const session = await auth()
        if (!session || !session.user || !session.user.id) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
        }

        const { prompt, model = "flux-dev", width = 1024, height = 1024 } = await req.json()

        if (!prompt) {
            return NextResponse.json({ error: "Prompt is required" }, { status: 400 })
        }

        // 1. Check Credits
        const credits = await checkAndResetDailyCredits(session.user.id)
        // 2. Load Balancing Configuration
        // Parse workers from Environment Variable (comma separated) or default to known instances
        const envWorkers = process.env.CLOUDFLARE_WORKER_URL
            ? process.env.CLOUDFLARE_WORKER_URL.split(",").map(url => url.trim())
            : []

        // Add hardcoded fallbacks/extras if they aren't in the env
        // The user might put the primary in env and want to add others here or in env
        const extraWorkers = [
            "https://bitter-forest-7e87.bob17040246.workers.dev/"
        ]

        // Combine and Deduplicate
        const ALL_WORKERS = Array.from(new Set([...envWorkers, ...extraWorkers])).filter(url => url.length > 0)

        if (ALL_WORKERS.length === 0) {
            return NextResponse.json({ error: "Server configuration error: No worker URLs found" }, { status: 500 })
        }

        // Round-robin selection
        if (typeof (global as any).requestCounter === 'undefined') {
            (global as any).requestCounter = 0
        }

        const counter = (global as any).requestCounter++
        const selectedWorkerUrl = ALL_WORKERS[counter % ALL_WORKERS.length]

        console.log(`[LoadBalancer] Request #${counter} -> Using Worker ${counter % ALL_WORKERS.length + 1}/${ALL_WORKERS.length}: ${selectedWorkerUrl}`)

        // Clean up URL construction
        const baseUrl = selectedWorkerUrl.endsWith("/") ? selectedWorkerUrl.slice(0, -1) : selectedWorkerUrl
        // If model includes a slash, remove it for consistency
        const cleanModel = model.startsWith("/") ? model.slice(1) : model
        const url = `${baseUrl}/${cleanModel}`

        // Prepare payload with Negative Prompt
        const payload = {
            prompt,
            negative_prompt: DEFAULT_NEGATIVE_PROMPT, // Pass explicit negative prompt
            width,
            height,
            steps: 30
        }

        // For Flux models that might ignore negative_prompt, we can optionally append it to the prompt
        // IF the model is known to not support it. But standard practice is to send it separately first.

        const response = await fetch(url, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
        })
        // }

        if (!response.ok) {
            const errorText = await response.text()
            console.error("AI Generation failed:", errorText)
            return NextResponse.json({ error: "Image generation failed upstream" }, { status: 500 })
        }

        const result = await response.json()

        if (!result.success || !result.url) {
            return NextResponse.json({ error: "Image generation returned no URL" }, { status: 500 })
        }

        // 3. Deduct Credits (Success confirmed) - 5 credits per generation
        await deductCredits(session.user.id, 5)

        // 4. Save to Database
        const generation = await prisma.generation.create({
            data: {
                prompt,
                model,
                width,
                height,
                imageUrl: result.url,
                userId: session.user.id,
                isPublic: true, // Default to public as per requirement "gallery... new non auth users will be able to see"
            }
        })

        return NextResponse.json({
            success: true,
            url: generation.imageUrl,
            width: generation.width,
            height: generation.height,
            prompt: generation.prompt,
            model: generation.model
        })

    } catch (error) {
        console.error("Generate API error:", error)
        return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
    }
}