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

export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export const maxDuration = 120;

const NO_STORE_HEADERS = {
  "Cache-Control": "no-store, max-age=0",
};

export async function GET(request: Request) {
  const user = await getSessionUser();

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

  if (!isKavenixAdminEmail(user.email)) {
    return Response.json(
      { error: "forbidden", message: "최고관리자만 조회할 수 있습니다." },
      { status: 403, headers: NO_STORE_HEADERS },
    );
  }

  const searchParams = new URL(request.url).searchParams;
  const actionId = normalizeKavenixStatisticsActionId(searchParams.get("action"));

  if (!actionId) {
    return Response.json(
      { error: "invalid-query", message: "조회할 운영 항목이 올바르지 않습니다." },
      { status: 400, headers: NO_STORE_HEADERS },
    );
  }

  try {
    const detail = await getKavenixStatisticsActionDetail(actionId);
    return Response.json(
      { detail, ok: true },
      { status: 200, headers: NO_STORE_HEADERS },
    );
  } catch (error) {
    console.error("Unable to load Kavenix action detail", error);
    return Response.json(
      {
        error: "statistics-action-detail-load-failed",
        message: "운영 항목 상세 데이터를 불러오지 못했습니다.",
      },
      { status: 500, headers: NO_STORE_HEADERS },
    );
  }
}

export async function POST(request: Request) {
  const user = await getSessionUser();

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

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

  const body = (await request.json().catch(() => null)) as {
    actionId?: string;
    mailboxId?: number | string;
  } | null;
  const actionId = normalizeKavenixStatisticsActionId(body?.actionId);
  const mailboxId = Number(body?.mailboxId);

  if (
    (actionId !== "sync-errors" && actionId !== "content-sync-errors") ||
    !Number.isInteger(mailboxId) ||
    mailboxId <= 0
  ) {
    return Response.json(
      { error: "invalid-query", message: "재동기화할 메일함 정보가 올바르지 않습니다." },
      { status: 400, headers: NO_STORE_HEADERS },
    );
  }

  try {
    const mailbox = await getKavenixAdminMailboxById(mailboxId);

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

    const result = await syncAllMailboxFoldersByEmail(mailbox.accountEmail, {
      awaitHydration: true,
      mailboxId,
    });
    const detail = await getKavenixStatisticsActionDetail(actionId);
    const resolved = !detail.items.some((item) => item.id === String(mailboxId));

    if (!result.accepted) {
      return Response.json(
        { detail, error: "sync-in-progress", message: "이미 재동기화가 진행 중입니다.", ok: false },
        { status: 409, headers: NO_STORE_HEADERS },
      );
    }

    if (result.failedFolders.length > 0 || !resolved) {
      return Response.json(
        {
          detail,
          error: "sync-incomplete",
          message: "일부 폴더 동기화가 완료되지 않았습니다. 잠시 후 다시 시도해주세요.",
          ok: false,
          result,
        },
        { status: 409, headers: NO_STORE_HEADERS },
      );
    }

    return Response.json(
      { detail, ok: true, result },
      { status: 200, headers: NO_STORE_HEADERS },
    );
  } catch (error) {
    console.error(`Unable to retry mailbox synchronization mailbox=${mailboxId}`, error);
    return Response.json(
      {
        error: "mailbox-sync-retry-failed",
        message: "메일함 재동기화를 완료하지 못했습니다.",
        ok: false,
      },
      { status: 503, headers: NO_STORE_HEADERS },
    );
  }
}
