import { getSessionUser } from "@/lib/auth";
import {
  getKavenixAdminMailboxById,
  isKavenixAdminEmail
} from "@/lib/kavenix-admin";
import { syncAllMailboxFoldersByEmail } from "@/lib/official-mail";

export const runtime = "nodejs";
export const maxDuration = 300;

export async function POST(
  _request: Request,
  context: { params: Promise<{ mailboxId: string }> }
) {
  const user = await getSessionUser();

  if (!user) {
    return Response.json(
      { error: "unauthorized", message: "로그인이 필요합니다." },
      { status: 401 }
    );
  }

  if (!isKavenixAdminEmail(user.email)) {
    return Response.json(
      { error: "forbidden", message: "최고관리자만 메일함을 재동기화할 수 있습니다." },
      { status: 403 }
    );
  }

  const { mailboxId } = await context.params;
  const parsedMailboxId = Number(mailboxId);
  const mailbox = await getKavenixAdminMailboxById(parsedMailboxId);

  if (!mailbox) {
    return Response.json(
      { error: "not-found", message: "재동기화할 메일함을 찾을 수 없습니다." },
      { status: 404 }
    );
  }

  try {
    const result = await syncAllMailboxFoldersByEmail(mailbox.accountEmail, {
      awaitHydration: true,
      mailboxId: mailbox.id
    });

    if (!result.accepted) {
      return Response.json(
        {
          error: "sync-in-progress",
          message: "이미 재동기화가 진행 중입니다. 잠시 후 다시 확인해주세요."
        },
        { status: 409 }
      );
    }

    if (result.failedFolders.length > 0 || Number(result.contentErrorCount ?? 0) > 0) {
      return Response.json(
        {
          error: "sync-incomplete",
          message: `일부 폴더를 복구하지 못했습니다. 자동 재시도를 예약했습니다.`,
          ok: false,
          result
        },
        { status: 409 }
      );
    }

    return Response.json({
      message: `${mailbox.email} 메일함의 목록과 본문·첨부파일 동기화를 완료했습니다.`,
      ok: true,
      result
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : "mailbox-sync-failed";
    console.error(`[kavenix-mailbox-sync] mailbox=${mailbox.id} message=${message}`);
    return Response.json(
      {
        error: "mailbox-sync-failed",
        message: "재동기화를 완료하지 못했습니다. 자동 재시도를 예약했습니다."
      },
      { status: 500 }
    );
  }
}
