import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { HttpError, requireAuthContext } from "@/lib/auth/authContext";
import { api } from "@/lib/convex/api";
import { getConvexAuthedHttpClient } from "@/lib/convex/server";

export const dynamic = "force-dynamic";

interface EmptyTrashPayload {
  workspaceId?: string;
}

function makeExpiredDeletedAtForForceEmpty(): string {
  // “清空附件垃圾桶”是一个显式的强制操作：直接清空所有垃圾桶内的表格，不受 10 分钟宽限期限制。
  // Convex 侧按 `deleted_at <= expiredDeletedAt` 做过滤，因此这里给一个很靠后的时间上界即可。
  return new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 100).toISOString();
}

export async function POST(request: Request) {
  if (!isConvexEnabled()) {
    return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
  }

  let auth;
  try {
    auth = await requireAuthContext();
  } catch (err) {
    if (err instanceof HttpError) {
      return NextResponse.json({ error: "未登录" }, { status: err.status });
    }
    return NextResponse.json({ error: "未登录" }, { status: 401 });
  }

  const { workspaceId }: EmptyTrashPayload = await request.json().catch(() => ({}));
  if (!workspaceId) {
    return NextResponse.json({ error: "缺少 workspaceId" }, { status: 400 });
  }

  const client = await getConvexAuthedHttpClient();
  try {
    const res = await client.mutation(api.tables.emptyTrashByWorkspace, {
      userId: auth.userId,
      workspaceId,
      expiredDeletedAt: makeExpiredDeletedAtForForceEmpty(),
    });
    return NextResponse.json({ success: true, ...(res as any) });
  } catch (err) {
    const message = err instanceof Error ? err.message : "清空失败";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
