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

type UndoMailboxMovePayload = {
  restoreFolder?: string;
};

export async function POST(request: Request, context: { params: Promise<{ jobId: string }> }) {
  const user = await getSessionUser();
  if (!user) {
    return Response.json({ error: "unauthorized", ok: false }, { status: 401 });
  }

  const payload = (await request.json().catch(() => null)) as UndoMailboxMovePayload | null;

  try {
    const { jobId } = await context.params;
    const result = await undoMailboxMessageMoveJobByEmail(user.email, jobId, payload?.restoreFolder);
    return Response.json({ ok: true, ...result }, { status: result.retry ? 202 : 200 });
  } catch (error) {
    const detail = error instanceof Error ? error.message : "job-undo-failed";
    const errorCode =
      detail === "job-not-found"
        ? detail
        : detail === "job-undo-unavailable"
          ? detail
          : detail === "mailbox-state-changed"
            ? detail
            : "job-undo-failed";
    const message =
      errorCode === "job-not-found"
        ? "실행 취소할 작업을 찾지 못했습니다."
        : errorCode === "job-undo-unavailable"
          ? "이미 영구 삭제되었거나 실행 취소할 수 없는 작업입니다."
          : errorCode === "mailbox-state-changed"
            ? "다른 기기에서 메일 상태가 변경되어 실행 취소할 수 없습니다."
            : "메일 작업을 실행 취소하지 못했습니다.";

    return Response.json(
      { error: errorCode, message, ok: false },
      {
        status: errorCode === "job-not-found" ? 404 : errorCode === "job-undo-failed" ? 500 : 409
      }
    );
  }
}
