import { prisma } from "@/lib/prisma"; import { publishPost } from "@/lib/instagram-publisher"; import { unlink } from "fs/promises"; import path from "path"; import { getServerSession } from "next-auth"; import { authOptions } from "@/lib/auth"; import { NextRequest, NextResponse } from "next/server"; export async function POST(req: NextRequest) { const session = await getServerSession(authOptions); if (!session?.user?.email) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } try { const body = await req.json(); const { instagramAccountId, caption, mediaUrl, mediaType, coverUrl, scheduledAt } = body; // Verify ownership const user = await prisma.user.findUnique({ where: { email: session.user.email }, include: { instagramAccounts: true }, }); const account = user?.instagramAccounts.find(a => a.id === instagramAccountId); if (!account) { return NextResponse.json({ error: "Invalid account" }, { status: 403 }); } // Create Post const post = await prisma.post.create({ data: { caption, mediaUrl, mediaType, coverUrl, scheduledAt: scheduledAt ? new Date(scheduledAt) : null, status: scheduledAt ? "SCHEDULED" : "DRAFT", instagramAccountId, }, }); // "Post Now" request (no scheduledAt) -> Publish immediately if (!scheduledAt && post.status === "DRAFT") { // In Vercel, ideally we'd offload this, but for MVP we await it. // If it fails, status remains DRAFT/FAILED. try { const published = await publishPost(post.id); return NextResponse.json(published); } catch (e) { // Return the post but with error? Or fail the request? // If we fail the request, UI should show error. return NextResponse.json({ error: "Failed to publish to Instagram" }, { status: 500 }); } } return NextResponse.json(post); } catch (error) { console.error("Create Post Error", error); return NextResponse.json({ error: "Internal Server Error" }, { status: 500 }); } } export async function GET(req: NextRequest) { // Implementation for listing posts (Dashboard needs this? Or we used server component fetching?) // Provide an API for flexibility. const session = await getServerSession(authOptions); if (!session?.user?.email) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); const user = await prisma.user.findUnique({ where: { email: session.user.email }, include: { instagramAccounts: { include: { posts: { orderBy: { createdAt: 'desc' } } } } }, }); // ... GET method ... const posts = user?.instagramAccounts.flatMap(acc => acc.posts) || []; return NextResponse.json(posts); } export async function DELETE(req: NextRequest) { const session = await getServerSession(authOptions); if (!session?.user?.email) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); const { searchParams } = new URL(req.url); const id = searchParams.get("id"); if (!id) return NextResponse.json({ error: "Missing ID" }, { status: 400 }); const user = await prisma.user.findUnique({ where: { email: session.user.email }, include: { instagramAccounts: true }, }); // Check ownership by verifying the post belongs to one of user's accounts const post = await prisma.post.findUnique({ where: { id } }); if (!post) return NextResponse.json({ error: "Not found" }, { status: 404 }); const ownsAccount = user?.instagramAccounts.some(acc => acc.id === post.instagramAccountId); if (!ownsAccount) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); // Delete await prisma.post.delete({ where: { id } }); // File Cleanup try { const mediaUrls = (post.mediaUrl || "").split(","); if (post.coverUrl) mediaUrls.push(post.coverUrl); for (const url of mediaUrls) { // Check if it's a local upload if (url.includes("/uploads/")) { const filename = url.split("/uploads/")[1]; if (filename) { const filepath = path.join(process.cwd(), "public", "uploads", filename); await unlink(filepath).catch(e => console.error("Failed to delete file:", filepath, e)); } } } } catch (e) { console.error("Error cleaning up files for post", id, e); } // TODO: Remove from Queue if it was scheduled (BullMQ remove is tricky without jobID, assumes jobID=postID or linear search) // For now, if we delete DB logic, the worker might fail when it tries to find the post, which is acceptable for MVP. // Ideally we stored jobId in DB. return NextResponse.json({ success: true }); } export async function PUT(req: NextRequest) { const session = await getServerSession(authOptions); if (!session?.user?.email) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); try { const body = await req.json(); const { id, caption, scheduledAt, mediaUrl, mediaType, coverUrl } = body; const user = await prisma.user.findUnique({ where: { email: session.user.email }, include: { instagramAccounts: true }, }); const post = await prisma.post.findUnique({ where: { id } }); if (!post) return NextResponse.json({ error: "Not found" }, { status: 404 }); const ownsAccount = user?.instagramAccounts.some(acc => acc.id === post.instagramAccountId); if (!ownsAccount) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); const newScheduledAt = scheduledAt ? new Date(scheduledAt) : null; let status = post.status; // Keep existing status by default unless scheduled change // If switching TO scheduled if (newScheduledAt) { status = "SCHEDULED"; } // If switching FROM scheduled to Post Now (null scheduledAt) // If the user deliberately removes scheduledAt, do they want to draft it or publish it? // Usually, in edit mode, if they remove date, it likely becomes DRAFT. else if (post.status === "SCHEDULED") { status = "DRAFT"; } const updated = await prisma.post.update({ where: { id }, data: { caption, scheduledAt: newScheduledAt, status, mediaUrl, // Allow updating media mediaType, coverUrl }, }); // NOTE: We do not auto-publish here if they remove schedule. They must explicitly hit "Post Now" which usually hits a separate endpoint or uses the POST endpoint for new posts? // But wait, the specific UI `PostCreator` handles `handleSubmit` which calls `POST` (create new) or `PUT` (edit). // If they click "Post Now" (saving with scheduledAt=null), the `handleSubmit` calls `PUT` with `scheduledAt: null`. // So we should check if they intend to publish immediately on edit. // `PostCreator.tsx` logic: // if initialPost exists -> PUT. // If user clicks "Post Now" -> scheduledAt is null. // So here, if `newScheduledAt` is null and they are submitting, it implies immediate publish? // However, standard PUT usually just updates. // Let's assume on Edit, "Post Now" means we should update AND publish. // But distinguishing "Save Draft" vs "Post Now" in PUT is tricky without extra flag. // `PostCreator` sends `scheduledAt: null` for both Draft and Post Now? // Wait, `PostCreator` logic: // It has `scheduledAt` state. // If "Save Draft", usually maps to status=DRAFT? The button just says "Save Draft". That logic isn't wired to send "Draft" status explicitly, it relies on scheduledAt? // Actually `PostCreator` buttons: // "Save Draft" -> submits? No, the code says "Save Draft" but it's just a button. Wait. // In `PostCreator`: Left button "Save Draft". Right button: "Post Now" / "Schedule Post". // Both trigger `handleSubmit`. // BUT `PostCreator` doesn't seem to differentiate "Save Draft" button click from "Post Now" button via state. // Ah, "Save Draft" button logic in `PostCreator` is missing an `onClick` that sets a "draft" flag or prevents default submission? // Actually, looking at `PostCreator.tsx` again (from memory or recent read): // There is 'Save Draft' button but it submits same form? // If so, `scheduledAt` is null. // If we want "Post Now" to actually publish, we need to know. // For now, let's assume PUT only updates DB. If they want to publish an existing draft, they probably need a "Publish" action or `scheduledAt` in past? // OR: we publish if `status` is set to `PUBLISHED`? // Creating a "Post Now" from Edit page is ambiguous. // Safest: Just update DB. The Cron won't pick it up if DRAFT. // If they want to publish, they probably create a new post or we need a specific "Publish" endpoint. // Given constraints, leaving PUT as DB-only update is safer unless we modify UI to send explicit "ACTION: PUBLISH". return NextResponse.json(updated); } catch (error) { console.error("Update Error", error); return NextResponse.json({ error: "Internal Error" }, { status: 500 }); } }