import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import { validateContentForPlatforms } from "@/lib/social/validate-publish-content";

/** Pre-publish validation against platform media/content rules. */
export async function POST(request: Request) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = (await request.json()) as {
      platforms?: string[];
      caption?: string;
      imageUrl?: string | null;
      videoUrl?: string | null;
      videoDurationSeconds?: number | null;
      projectCountries?: string[];
    };

    const platforms = Array.isArray(body.platforms) ? body.platforms : [];
    if (!platforms.length) {
      return NextResponse.json({ error: "platforms[] is required" }, { status: 400 });
    }

    const results = validateContentForPlatforms(platforms, {
      caption: body.caption,
      imageUrl: body.imageUrl,
      videoUrl: body.videoUrl,
      videoDurationSeconds: body.videoDurationSeconds,
      projectCountries: body.projectCountries,
    });

    return NextResponse.json({
      ok: results.every((r) => r.ok),
      results,
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Validation failed";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
