import { getSessionUser } from "@/lib/auth";
import { moveAllMailboxMessagesFromSenderToTrashByEmail } from "@/lib/official-mail";

export async function POST(request: Request) {
  const user = await getSessionUser();
  if (!user) return Response.json({ error: "unauthorized", ok: false }, { status: 401 });
  const payload = (await request.json().catch(() => null)) as { action?: string; senderAddress?: string } | null;

  try {
    if (payload?.action !== "trash-all") {
      return Response.json({ error: "invalid-action", ok: false }, { status: 400 });
    }
    const result = await moveAllMailboxMessagesFromSenderToTrashByEmail(
      user.email,
      String(payload.senderAddress ?? "")
    );
    return Response.json({ ok: true, result });
  } catch (error) {
    const code = error instanceof Error ? error.message : "sender-action-failed";
    return Response.json(
      { error: code, message: "발신자 메일을 처리하지 못했습니다. 잠시 후 다시 시도해주세요.", ok: false },
      { status: 400 }
    );
  }
}
