Spaces:
Build error
Build error
| import { NextRequest, NextResponse } from "next/server"; | |
| import ZAI from "z-ai-web-dev-sdk"; | |
| import { db } from "@/lib/db"; | |
| import { validateUserCredit, logResourceUsage } from "@/lib/credits"; | |
| const FAMOUS_INFLUENCERS = [ | |
| { name: "Lil Miquela", handle: "@lilmiquela", platform: "Instagram", followers: 2500000, engagement: 3.2, niche: "Fashion", petCompanion: false, lessons: ["Consistencia visual", "Narrativa creible"] }, | |
| { name: "Rozy", handle: "@rozy.gram", platform: "Instagram", followers: 180000, engagement: 4.5, niche: "K-pop", petCompanion: true, petType: "dog", lessons: ["Tendencias K-pop", "Mascota como diferenciador"] }, | |
| { name: "Imma", handle: "@imma.gram", platform: "Instagram", followers: 390000, engagement: 3.8, niche: "Fashion & Art", petCompanion: false, lessons: ["Fusionar arte y moda"] }, | |
| { name: "Ayla", handle: "@ayla_virtual", platform: "TikTok", followers: 850000, engagement: 8.3, niche: "Dance", petCompanion: true, petType: "dog", lessons: ["Participar en trends", "Alta frecuencia"] } | |
| ]; | |
| export async function GET(request: NextRequest) { | |
| try { | |
| const { searchParams } = new URL(request.url); | |
| const niche = searchParams.get("niche"); | |
| const withPets = searchParams.get("withPets"); | |
| let influencers = [...FAMOUS_INFLUENCERS]; | |
| if (niche) influencers = influencers.filter(i => i.niche.toLowerCase().includes(niche.toLowerCase())); | |
| if (withPets === "true") influencers = influencers.filter(i => i.petCompanion); | |
| const dbInfluencers = await db.aIInfluencer.findMany({ where: { isActive: true } }); | |
| return NextResponse.json({ success: true, influencers, customInfluencers: dbInfluencers }); | |
| } catch { | |
| return NextResponse.json({ success: false, error: "Error" }, { status: 500 }); | |
| } | |
| } | |
| export async function POST(request: NextRequest) { | |
| try { | |
| const body = await request.json(); | |
| const { targetNiche, includePets, userId, tier = "free" } = body; | |
| // Validar créditos | |
| const creditCheck = await validateUserCredit(db, userId || "anonymous", "influencers_per_month", tier); | |
| if (!creditCheck.allowed) { | |
| return NextResponse.json({ success: false, error: creditCheck.reason, remaining: creditCheck.remaining }, { status: 429 }); | |
| } | |
| const zai = await ZAI.create(); | |
| // Generar análisis Y datos del influencer automáticamente | |
| const completion = await zai.chat.completions.create({ | |
| messages: [ | |
| { | |
| role: "system", | |
| content: `Eres experto en crear influencers virtuales. Responde SOLO con JSON válido (sin markdown): | |
| { | |
| "name": "nombre único del influencer", | |
| "handle": "@handle", | |
| "platform": "Instagram|TikTok|YouTube", | |
| "followers": número, | |
| "engagement": número entre 0-10, | |
| "niche": "nicho específico", | |
| "style": "descripción del estilo", | |
| "contentTypes": "tipos de contenido", | |
| "postingSchedule": "frecuencia de posts", | |
| "visualStyle": "descripción visual", | |
| "monetizationType": "tipo de monetización", | |
| "signatureElements": "elementos únicos", | |
| "petCompanion": boolean, | |
| "petType": "tipo de mascota o null" | |
| }` | |
| }, | |
| { | |
| role: "user", | |
| content: `Crea un influencer único para el nicho: ${targetNiche || "general"}. ${includePets ? "Que tenga mascota." : "Sin mascota."} Hazlo creativo y único.` | |
| } | |
| ], | |
| temperature: 0.9, | |
| max_tokens: 1200 | |
| }); | |
| let influencerData: Record<string, any> = { | |
| name: "Influencer Generado", | |
| platform: "Instagram", | |
| niche: targetNiche || "general", | |
| petCompanion: includePets || false | |
| }; | |
| try { | |
| const content = completion.choices[0]?.message?.content || ""; | |
| const jsonMatch = content.match(/\{[\s\S]*\}/); | |
| if (jsonMatch) { | |
| const parsed = JSON.parse(jsonMatch[0]); | |
| influencerData = { ...influencerData, ...parsed }; | |
| } | |
| } catch (parseError) { | |
| console.warn("Error parsing influencer data, using defaults", parseError); | |
| } | |
| // Crear influencer automáticamente | |
| const influencer = await db.aIInfluencer.create({ | |
| data: { | |
| name: influencerData.name, | |
| handle: influencerData.handle || null, | |
| platform: influencerData.platform, | |
| followers: influencerData.followers || null, | |
| engagement: influencerData.engagement || null, | |
| niche: influencerData.niche, | |
| style: influencerData.style || null, | |
| contentTypes: influencerData.contentTypes ? JSON.stringify(influencerData.contentTypes) : null, | |
| postingSchedule: influencerData.postingSchedule || null, | |
| visualStyle: influencerData.visualStyle || null, | |
| monetizationType: influencerData.monetizationType || null, | |
| signatureElements: influencerData.signatureElements ? JSON.stringify(influencerData.signatureElements) : null, | |
| petCompanion: influencerData.petCompanion || false, | |
| petType: influencerData.petType || null, | |
| } | |
| }); | |
| // Log del uso de crédito | |
| await logResourceUsage(db, userId || "anonymous", "influencers_per_month", influencer.id); | |
| // Registrar tarea completada | |
| await db.agentTask.create({ | |
| data: { | |
| type: "create_influencer", | |
| status: "completed", | |
| input: targetNiche || "general", | |
| output: influencer.id, | |
| completedAt: new Date() | |
| } | |
| }); | |
| return NextResponse.json({ | |
| success: true, | |
| influencer, | |
| creditsRemaining: creditCheck.remaining ? creditCheck.remaining - 1 : 0 | |
| }); | |
| } catch (error: unknown) { | |
| const message = error instanceof Error ? error.message : "Error desconocido"; | |
| return NextResponse.json({ success: false, error: message }, { status: 500 }); | |
| } | |
| } | |
| export async function PUT(request: NextRequest) { | |
| try { | |
| const body = await request.json(); | |
| const { name, handle, platform, followers, engagement, niche, petCompanion, petType } = body; | |
| const influencer = await db.aIInfluencer.create({ | |
| data: { | |
| name, handle: handle || null, platform, followers: followers || null, | |
| engagement: engagement || null, niche: niche || null, | |
| petCompanion: petCompanion || false, petType: petType || null | |
| } | |
| }); | |
| return NextResponse.json({ success: true, influencer }); | |
| } catch { | |
| return NextResponse.json({ success: false, error: "Error" }, { status: 500 }); | |
| } | |
| } |