import { NextRequest, NextResponse } from "next/server"; import { db } from "@/lib/db"; import ZAI from "z-ai-web-dev-sdk"; export async function GET(request: NextRequest) { try { const { searchParams } = new URL(request.url); const status = searchParams.get("status"); const platform = searchParams.get("platform"); const where: Record = {}; if (status) where.status = status; if (platform) where.platformId = platform; const posts = await db.post.findMany({ where, orderBy: { createdAt: "desc" }, take: 50 }); return NextResponse.json({ success: true, posts }); } catch { return NextResponse.json({ success: false, error: "Error" }, { status: 500 }); } } export async function POST(request: NextRequest) { try { const body = await request.json(); const { title, type, caption, scheduledAt, platformId, autoGenerateCaption } = body; if (!title) { return NextResponse.json({ success: false, error: "Titulo requerido" }, { status: 400 }); } let finalCaption: string | null = caption || null; if (autoGenerateCaption && !caption) { try { const zai = await ZAI.create(); const completion = await zai.chat.completions.create({ messages: [ { role: "system", content: "Eres un experto en redes sociales. Genera un caption atractivo." }, { role: "user", content: "Caption para: " + title } ] }); finalCaption = completion.choices[0]?.message?.content || null; } catch {} } const post = await db.post.create({ data: { title, caption: finalCaption, type: type || "post", status: scheduledAt ? "scheduled" : "draft", platformId: platformId || null, scheduledAt: scheduledAt ? new Date(scheduledAt) : null } }); return NextResponse.json({ success: true, post }); } catch { return NextResponse.json({ success: false, error: "Error" }, { status: 500 }); } } export async function PUT(request: NextRequest) { try { const body = await request.json(); const { id, status, publishedAt } = body; if (!id) return NextResponse.json({ success: false, error: "ID requerido" }, { status: 400 }); const data: { status?: string; publishedAt?: Date } = {}; if (status) data.status = status; if (publishedAt) data.publishedAt = new Date(publishedAt); const post = await db.post.update({ where: { id }, data }); return NextResponse.json({ success: true, post }); } catch { return NextResponse.json({ success: false, error: "Error" }, { status: 500 }); } } export async function DELETE(request: NextRequest) { try { const { searchParams } = new URL(request.url); const id = searchParams.get("id"); if (!id) return NextResponse.json({ success: false, error: "ID requerido" }, { status: 400 }); await db.post.delete({ where: { id } }); return NextResponse.json({ success: true }); } catch { return NextResponse.json({ success: false, error: "Error" }, { status: 500 }); } }