Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
262 changes: 183 additions & 79 deletions app/api/generate/route.ts
Original file line number Diff line number Diff line change
@@ -1,119 +1,223 @@
// ─── Post Generation Endpoint ─────────────────────────────────────────────────
// Handles structured (non-streaming) post generation for the dashboard.
// Response shape: { post: string; hashtags: string[]; platform: string }

import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/prisma";
import { getSessionEmail } from "@/lib/session";
import { appendPost, canUserPost } from "@/lib/db";
import { getPlan, isUnlimited } from "@/lib/plans";
import { anthropic } from "@ai-sdk/anthropic";
import { google } from "@ai-sdk/google";
import { Anthropic } from "@anthropic-ai/sdk";
import { generateText } from "ai";
import { trace, generateRequestId } from "@/lib/trace";

// ─── Schema ───────────────────────────────────────────────────────────────────

const generateSchema = z.object({
prompt: z.string().min(5),
platform: z.enum(["x", "facebook", "instagram", "linkedin", "threads"]),
prompt: z.string().trim().min(5, "Prompt must be at least 5 characters").max(600),
platform: z.enum(["x", "instagram", "linkedin", "facebook", "threads", "tiktok", "youtube"]),
});

type Platform = z.infer<typeof generateSchema>["platform"];

// ─── Platform-specific system prompts ────────────────────────────────────────

const PLATFORM_CONTEXT: Record<Platform, string> = {
x: "X (Twitter) — max 280 characters, punchy hook, conversational tone, 1–3 hashtags",
instagram: "Instagram — engaging caption up to 2200 characters, storytelling tone, 5–10 hashtags",
linkedin: "LinkedIn — professional thought leadership post, 150–300 words, 3–5 hashtags",
facebook: "Facebook — community-friendly, conversational, 100–200 words, 2–4 hashtags",
threads: "Threads — conversational short-form, max 500 characters, 0–2 hashtags",
tiktok: "TikTok — viral hook for video caption, max 150 characters, 3–5 trending hashtags",
youtube: "YouTube — SEO-friendly video description, 200–300 words, 5–8 hashtags",
};

// ─── Model routing by plan tier ──────────────────────────────────────────────

function resolveModel(planId: string) {
const isAgencyTier =
planId === "agency_monthly" ||
planId === "agency_yearly" ||
planId === "agency_lifetime";

if (isAgencyTier && process.env.ANTHROPIC_API_KEY) {
return { model: anthropic("claude-3-5-sonnet-20241022"), provider: "claude" as const };
}
if (process.env.GOOGLE_GENERATIVE_AI_API_KEY) {
return { model: google("gemini-2.0-flash"), provider: "gemini" as const };
}
if (process.env.ANTHROPIC_API_KEY) {
return { model: anthropic("claude-3-5-sonnet-20241022"), provider: "claude" as const };
}
return null;
Comment on lines +45 to +54
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The resolveModel function incorrectly falls back to Gemini if the ANTHROPIC_API_KEY is missing for an Agency tier user. This should explicitly return null or throw an error to prevent unexpected behavior for premium users.

if (isAgencyTier) {
    if (!process.env.ANTHROPIC_API_KEY) return null;
    return { model: anthropic("claude-3-5-sonnet-20241022"), provider: "claude" as const };
  }
  if (process.env.GOOGLE_GENERATIVE_AI_API_KEY) {
    return { model: google("gemini-2.0-flash"), provider: "gemini" as const };
  }
  if (process.env.ANTHROPIC_API_KEY) {
    return { model: anthropic("claude-3-5-sonnet-20241022"), provider: "claude" as const };
  }
  return null;

}

// ─── Response parser: extract post + hashtags from raw AI text ────────────────

function parseAIResponse(raw: string): { post: string; hashtags: string[] } {
// Try JSON block first (wrapped in ```json ... ```)
const jsonBlock = raw.match(/```json\s*([\s\S]*?)```/i);
if (jsonBlock?.[1]) {
try {
const parsed = JSON.parse(jsonBlock[1].trim());
if (typeof parsed.post === "string") {
return {
post: parsed.post.trim(),
hashtags: Array.isArray(parsed.hashtags) ? parsed.hashtags : [],
};
}
} catch { /* fall through */ }
}

// Try raw JSON object
const jsonRaw = raw.match(/\{[\s\S]*\}/);
if (jsonRaw) {
try {
const parsed = JSON.parse(jsonRaw[0]);
if (typeof parsed.post === "string") {
return {
post: parsed.post.trim(),
hashtags: Array.isArray(parsed.hashtags) ? parsed.hashtags : [],
};
}
} catch { /* fall through */ }
}

// Fallback: use raw text as post, extract hashtags via regex
const hashtags = (raw.match(/#\w+/g) ?? []).map((h) => h.replace("#", ""));
const postText = raw.trim();
return { post: postText, hashtags };
}

// ─── Route Handler ────────────────────────────────────────────────────────────

export async function POST(request: Request) {
const requestId = generateRequestId();
const req = request as NextRequest;

try {
// 1. التحقق من هوية المستخدم ومطابقة الـ Schema الفعلية لقاعدة البيانات
// ── Auth ────────────────────────────────────────────────────────────────────
const email = await getSessionEmail();
if (!email) {
return NextResponse.json({ error: "Unauthorized. Please sign in." }, { status: 401 });
}

const user = await prisma.user.findUnique({ where: { email } });

// If they are on the free/starter plan AND their status is explicitly 'trial' (expired/restricted), block them.
// Paid plans bypass this check even if the database default hasn't updated yet.
// ── User resolution ─────────────────────────────────────────────────────────
const user = await prisma.user.findUnique({ where: { email: email.toLowerCase() } });
if (!user) {
return NextResponse.json({ error: "User not found." }, { status: 404 });
return NextResponse.json({ error: "User account not found." }, { status: 404 });
}

if (user.plan === "free" && user.status === "trial") {
return NextResponse.json({ error: "Your free trial has ended. Please upgrade your plan!" }, { status: 403 });
// ── Validate request body ───────────────────────────────────────────────────
let rawBody: unknown;
try {
rawBody = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body." }, { status: 400 });
}

const body = await request.json();
const parseResult = generateSchema.safeParse(body);
const parseResult = generateSchema.safeParse(rawBody);
if (!parseResult.success) {
return NextResponse.json({ error: "Invalid platform or prompt configuration." }, { status: 400 });
return NextResponse.json(
{
error: "Invalid request parameters.",
detail: parseResult.error.flatten().fieldErrors,
},
{ status: 400 },
);
}

const { prompt, platform } = parseResult.data;

// 2. حارس المنصات الخاص بباقة الـ Lifetime (حظر LinkedIn و Threads)
if (user.plan === "lifetime") {
const allowedPlatforms = ["x", "facebook", "instagram"];
if (!allowedPlatforms.includes(platform)) {
return NextResponse.json({
error: `Your Lifetime plan unlocks X, Facebook, and Instagram only. Upgrade to Agency to unlock ${platform.toUpperCase()}!`,
}, { status: 403 });
}
// ── Plan resolution (handles all plan ID formats) ────────────────────────────
const plan = getPlan(user.plan, user.email);

// ── Usage limit check ────────────────────────────────────────────────────────
const usage = await canUserPost(user.id, user.plan);
if (!usage.allowed) {
return NextResponse.json(
{ error: usage.reason, limitReached: true },
{ status: 403 },
);
}

let generatedOutput = "";
const systemInstruction = `You are an expert social media copywriter. Write a high-converting post optimized specifically for ${platform.toUpperCase()}.`;
// ── Platform access check (free plan: 2 platforms only) ─────────────────────
const freePlatforms: Platform[] = ["x", "linkedin"];
if (plan.id === "free" && !freePlatforms.includes(platform)) {
return NextResponse.json(
{
error: `Your Starter plan supports X and LinkedIn only. Upgrade to unlock ${platform}.`,
limitReached: false,
},
{ status: 403 },
);
}

// 3. التوجيه الديناميكي المتوافق مع الـ Engines والموديلات المخفية
if (user.plan === "agency") {
// عملاء النخبة: Claude 3.5 Sonnet عبر الـ Anthropic SDK المباشر
const anthropicKey = process.env.ANTHROPIC_API_KEY;
if (!anthropicKey) {
return NextResponse.json({ error: "Elite AI Engine configuration missing." }, { status: 500 });
}
// ── Model selection ─────────────────────────────────────────────────────────
const modelConfig = resolveModel(user.plan);
if (!modelConfig) {
return NextResponse.json(
{ error: "AI engine is not configured. Contact support." },
{ status: 503 },
);
}

const anthropic = new Anthropic({ apiKey: anthropicKey });
const completion = await anthropic.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1000,
messages: [{ role: "user", content: `${systemInstruction}\n\nUser Request: ${prompt}` }],
});

const block = completion.content[0];
generatedOutput = block.type === "text" ? block.text : "No text generated";
} else if (user.plan === "pro" || user.plan === "lifetime") {
// الفئة المتوسطة وعرض الـ Pi اللحظي: Gemini 1.5 Pro عبر Vercel AI SDK
if (!process.env.GOOGLE_GENERATIVE_AI_API_KEY) {
return NextResponse.json({ error: "Advanced AI Engine configuration missing." }, { status: 500 });
}
trace({
requestId,
event: "generate.start",
provider: modelConfig.provider,
planId: user.plan,
platform,
});

const { text } = await generateText({
model: google("models/gemini-1.5-pro"),
prompt: `${systemInstruction}\n\nUser Request: ${prompt}`,
});
generatedOutput = text;
} else {
// الفئة المجانية والـ Starter الاقتصادي: Gemini 1.5 Flash الخفيف
if (!process.env.GOOGLE_GENERATIVE_AI_API_KEY) {
return NextResponse.json({ error: "Standard AI Engine configuration missing." }, { status: 500 });
}
// ── Build prompt ─────────────────────────────────────────────────────────────
const systemPrompt = `You are an expert social media copywriter specializing in ${PLATFORM_CONTEXT[platform]}.

const { text } = await generateText({
model: google("models/gemini-1.5-flash"),
prompt: `${systemInstruction}\n\nUser Request: ${prompt}`,
});
generatedOutput = text;
}
Your task: write a high-converting post for the platform context described above based on the user's idea.

Return ONLY a JSON object in this exact format (no markdown, no explanation, just the JSON):
{
"post": "<the full post text, ready to copy-paste>",
"hashtags": ["hashtag1", "hashtag2"]
}

// 4. الحفظ في الـ Table الصحيح تماماً (prisma.auditLog) لمنع كسر الداتابيز
await prisma.auditLog.create({
data: {
userId: user.id,
action: `GENERATE_POST_${platform.toUpperCase()}`,
metadata: {
prompt,
characterCount: generatedOutput.length,
platform,
} as any,
ip: (request as NextRequest).headers.get("x-forwarded-for") ?? undefined,
},
Rules:
- The "hashtags" array must NOT include the # symbol — just the words.
- The "post" field should include inline hashtags naturally if appropriate for the platform.
- Never exceed platform character limits.`;

// ── Generate ─────────────────────────────────────────────────────────────────
const start = Date.now();
const { text: rawOutput } = await generateText({
model: modelConfig.model,
system: systemPrompt,
prompt: `User idea: ${prompt}`,
});

return NextResponse.json({
success: true,
const durationMs = Date.now() - start;
trace({ requestId, event: "generate.complete", provider: modelConfig.provider, durationMs });

// ── Parse structured output ──────────────────────────────────────────────────
const { post, hashtags } = parseAIResponse(rawOutput);

// ── Persist post + increment counters ────────────────────────────────────────
await appendPost({
userId: user.id,
content: post,
platform,
content: generatedOutput,
prompt,
});
} catch (error) {
console.error("[FINAL_COMPLIANT_GENERATION_ERROR]:", error);
return NextResponse.json({ error: "Generation process encountered a schema alignment error." }, { status: 500 });

return NextResponse.json({ post, hashtags, platform, provider: modelConfig.provider });
} catch (error: unknown) {
const detail = error instanceof Error ? error.message : String(error);
trace({ requestId, event: "generate.error", error: detail });

return NextResponse.json(
{ error: "Failed to generate post.", detail },
{ status: 500 },
);
}
}
Loading
Loading