import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getActiveAccountId } from "@/lib/account-context";
import { apiRouteErrorResponse } from "@/lib/auth/api";
import { requireUserAccountScope } from "@/lib/auth/user-scope";
import { syncThreadsOwnPostsAndInsights } from "@/lib/services/threads-api-sync";

export async function GET() {
  try {
    const accountId = await getActiveAccountId();
    const { where } = await requireUserAccountScope(accountId);
    const replies = await prisma.inboundReply.findMany({
      where: { published: where },
      orderBy: [{ status: "asc" }, { createdAt: "desc" }],
      include: {
        published: true,
        replyDrafts: { orderBy: { createdAt: "desc" } },
      },
      take: 80,
    });

    return NextResponse.json({ replies });
  } catch (error) {
    return apiRouteErrorResponse(error, "engagement/replies");
  }
}

export async function POST(request: Request) {
  try {
    const body = (await request.json().catch(() => ({}))) as {
      sync?: boolean;
      postsLimit?: number;
      repliesLimit?: number;
    };

    if (body.sync) {
      const result = await syncThreadsOwnPostsAndInsights({
        postsLimit: body.postsLimit ?? 25,
        repliesLimit: body.repliesLimit ?? 25,
      });
      return NextResponse.json(result);
    }

    return NextResponse.json({ error: "缺少操作" }, { status: 400 });
  } catch (error) {
    return apiRouteErrorResponse(error, "engagement/replies/sync");
  }
}