import {
  getEnabledAiAssistOwnerEmails,
  processAiReplyRelaySweep,
} from "@/lib/mail-automation";
import { refreshMailboxByEmail } from "@/lib/official-mail";

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

type RelayRunRequest = {
  ownerEmail?: unknown;
  processReplies?: unknown;
  reason?: unknown;
  syncAllOwners?: unknown;
};

function hasValidCronSecret(request: Request) {
  const expected = process.env.OFFICIAL_MAIL_CRON_SECRET?.trim();

  if (!expected) {
    return false;
  }

  const provided = request.headers.get("x-officialmail-cron-secret")?.trim();
  return provided === expected;
}

export async function POST(request: Request) {
  if (!hasValidCronSecret(request)) {
    return Response.json(
      { error: "forbidden", message: "유효한 크론 시크릿이 필요합니다." },
      { status: 403 },
    );
  }

  try {
    const body = await request.json().catch(() => null) as RelayRunRequest | null;
    const hasExplicitWorkSelection = Boolean(
      body &&
      (
        Object.hasOwn(body, "ownerEmail") ||
        Object.hasOwn(body, "processReplies") ||
        Object.hasOwn(body, "syncAllOwners")
      ),
    );
    const requestedOwnerEmail =
      typeof body?.ownerEmail === "string"
        ? body.ownerEmail.trim().toLowerCase()
        : "";
    const shouldProcessReplies = hasExplicitWorkSelection
      ? body?.processReplies === true
      : true;
    const shouldSyncAllOwners = hasExplicitWorkSelection
      ? body?.syncAllOwners === true
      : true;
    const owners = await getEnabledAiAssistOwnerEmails();
    const ownersToSync = shouldSyncAllOwners
      ? owners
      : requestedOwnerEmail
        ? owners.filter((owner) => owner.ownerEmail === requestedOwnerEmail)
        : [];
    const syncResults = {
      failed: 0,
      synced: 0,
    };

    for (const owner of ownersToSync) {
      try {
        await refreshMailboxByEmail(owner.ownerEmail, { folder: "inbox" });
        syncResults.synced += 1;
      } catch {
        syncResults.failed += 1;
      }
    }

    const summary = shouldProcessReplies
      ? await processAiReplyRelaySweep()
      : {
          failed: 0,
          owners: 0,
          relayed: 0,
          skipped: 0,
        };

    return Response.json({
      ok: true,
      reason: typeof body?.reason === "string" ? body.reason.slice(0, 80) : null,
      summary: {
        ...summary,
        summarySyncFailed: syncResults.failed,
        summarySynced: syncResults.synced,
      },
    });
  } catch (error) {
    return Response.json(
      {
        error: "ai-reply-relay-run-failed",
        message:
          error instanceof Error ? error.message : "AI 답장 릴레이 실행에 실패했습니다.",
      },
      { status: 500 },
    );
  }
}
