import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import { runScheduledPublish } from "@/lib/scheduling/run-scheduled-publish";

export async function POST(request: Request) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const allowManual =
    process.env.ALLOW_MANUAL_AUTO_POST === "true" || process.env.NODE_ENV === "development";

  if (!allowManual) {
    return NextResponse.json(
      {
        error:
          "Manual auto-post is disabled on this server. Set ALLOW_MANUAL_AUTO_POST=true to enable.",
      },
      { status: 403 },
    );
  }

  if (!process.env.CRON_SECRET?.trim()) {
    return NextResponse.json(
      { error: "CRON_SECRET not configured — scheduler cannot run." },
      { status: 503 },
    );
  }

  const summary = await runScheduledPublish("manual", new Date(), {
    bypassSlotWindow: true,
  });
  return NextResponse.json({
    success: true,
    triggeredBy: user.id,
    ...summary,
    logFile: `logs/auto-post-${new Date().toISOString().slice(0, 10)}.log`,
  });
}
