/**
 * POST /api/social/ai/generate
 * Generate AI content (captions, hashtags, etc.)
 *
 * Data-source routing: WU-06 — Convex branch added for social domain.
 * Note: AI generation is an external API call (Google Gemini). The DB writes
 * (ai_content_generations) are inside the service layer and will be migrated
 * when the service itself is updated. The route-level Convex branch here is a
 * placeholder to ensure the data-source check is in place for future service
 * migration.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { SocialAIAssistantService } from "@/lib/services/social-ai-assistant.service";
import { aiGenerateSchema } from "@/lib/validators/social-media.validator";
import { getDataSource } from "@/lib/data-source";
import { logger } from "@/lib/logger";

export async function POST(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const body = await request.json();
    const parsed = aiGenerateSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        {
          success: false,
          error: "Validation failed",
          details: parsed.error.flatten(),
        },
        { status: 400 },
      );
    }

    // -- Convex data-source branch ------------------------------------------
    // AI generation itself is external (Gemini). The service writes to
    // ai_content_generations via Prisma internally. When DS_SOCIAL=convex,
    // the service layer will be updated to write to Convex. For now, the
    // route delegates to the same service regardless of data source.
    if (getDataSource("social") === "convex") {
      try {
        // Service-layer DB operations will be migrated separately.
        // For now, use the same service which writes via Prisma internally.
        const result = await SocialAIAssistantService.generateContent(
          user.userId,
          parsed.data,
        );
        return NextResponse.json({ success: true, data: result });
      } catch (error) {
        const message = error instanceof Error ? error.message : "";
        if (message === "AI_NOT_CONFIGURED") {
          return NextResponse.json(
            {
              success: false,
              error: "AI service is not configured. Please set GOOGLE_API_KEY.",
            },
            { status: 503 },
          );
        }
        logger.warn("[Convex fallback] social AI generate:", {
          error: message,
        });
        // Fall through to Prisma path
      }
    }

    // -- Prisma path (default) -----------------------------------------------
    const result = await SocialAIAssistantService.generateContent(
      user.userId,
      parsed.data,
    );
    return NextResponse.json({ success: true, data: result });
  } catch (error) {
    const message = error instanceof Error ? error.message : "";
    if (message === "AI_NOT_CONFIGURED") {
      return NextResponse.json(
        {
          success: false,
          error: "AI service is not configured. Please set GOOGLE_API_KEY.",
        },
        { status: 503 },
      );
    }
    logger.error("AI content generation failed", { error });
    return NextResponse.json(
      {
        success: false,
        error: "Content generation failed. Please try again.",
      },
      { status: 500 },
    );
  }
}
