import { loginOrCreateUser } from "@/lib/official-mail";
import { createAppSession } from "@/lib/app-auth";
import {
  enableLegacyNativeAppCompatibility,
  getOrCreateNativeMailboxAppPassword,
} from "@/lib/mail-external-access";
import {
  getAuthRequestMetadata,
  recordUserAuthActivity,
} from "@/lib/auth-activity";
import {
  getAppUpdateDecision,
  getAppVersionPolicy,
  isAppPlatform,
  isLegacyNativeAuthEnabled,
} from "@/lib/app-version-policy";

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

type AppLoginRequest = {
  email?: string;
  password?: string;
};

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

function invalidCredentialsResponse() {
  return Response.json(
    {
      error: "invalid-credentials",
      message: "이메일 또는 비밀번호가 올바르지 않습니다.",
    },
    { status: 401, headers: NO_STORE_HEADERS },
  );
}

export async function POST(request: Request) {
  let body: AppLoginRequest;

  try {
    body = await request.json();
  } catch {
    return Response.json(
      { error: "invalid-request", message: "로그인 요청 형식이 올바르지 않습니다." },
      { status: 400, headers: NO_STORE_HEADERS },
    );
  }

  const email = String(body.email ?? "").trim().toLowerCase();
  const password = String(body.password ?? "");

  if (!email || !password) {
    return invalidCredentialsResponse();
  }

  const authRequestMetadata = getAuthRequestMetadata(request.headers, "app");
  const usesNativeCredential = request.headers.get("x-officialmail-native-auth") === "v2";
  const isLegacyNativeClient = /^Dart\/\d+(?:\.\d+)* \(dart:io\)$/.test(
    request.headers.get("user-agent")?.trim() ?? "",
  );

  if (!usesNativeCredential && !isLegacyNativeClient) {
    return Response.json(
      { error: "unsupported-app-client", message: "지원하지 않는 앱 연결 방식입니다." },
      { status: 400, headers: NO_STORE_HEADERS },
    );
  }

  if (!usesNativeCredential && !(await isLegacyNativeAuthEnabled())) {
    return Response.json(
      {
        error: "app-update-required",
        message: "이 버전의 오피셜메일 앱은 더 이상 지원되지 않습니다. 스토어에서 최신 버전으로 업데이트해주세요.",
      },
      { status: 426, headers: NO_STORE_HEADERS },
    );
  }

  if (usesNativeCredential) {
    const platform = request.headers.get("x-officialmail-app-platform");
    const version = request.headers.get("x-officialmail-app-version") ?? "";
    const build = Number(request.headers.get("x-officialmail-app-build"));
    if (!isAppPlatform(platform) || !/^\d+\.\d+\.\d+$/.test(version) || !Number.isSafeInteger(build)) {
      return Response.json(
        { error: "app-version-required", message: "앱 버전을 확인할 수 없습니다. 최신 버전으로 업데이트해주세요." },
        { status: 426, headers: NO_STORE_HEADERS },
      );
    }
    const policy = await getAppVersionPolicy(platform);
    if (getAppUpdateDecision(policy, version, build) === "required") {
      return Response.json(
        { error: "app-update-required", message: "계속 사용하려면 오피셜메일 앱을 최신 버전으로 업데이트해주세요." },
        { status: 426, headers: NO_STORE_HEADERS },
      );
    }
  }

  try {
    const user = await loginOrCreateUser({ email, password });
    const nativeImapPassword = usesNativeCredential
      ? await getOrCreateNativeMailboxAppPassword(user.email)
      : null;
    if (!usesNativeCredential) {
      await enableLegacyNativeAppCompatibility(user.email, password);
    }
    const session = await createAppSession(user.email);
    await recordUserAuthActivity({
      ...authRequestMetadata,
      eventType: "login",
      identityEmail: email,
      lookup: "login_email",
      outcome: "success",
    });
    return Response.json(
      { ok: true, session, user, ...(nativeImapPassword ? { nativeImapPassword } : {}) },
      { status: 200, headers: NO_STORE_HEADERS },
    );
  } catch (error) {
    const outcome =
      error instanceof Error &&
      (error.message === "invalid-password" || error.message === "required")
        ? "invalid_credentials"
        : error instanceof Error && error.message === "growth-plan-required"
          ? "plan_restricted"
          : "error";
    await recordUserAuthActivity({
      ...authRequestMetadata,
      eventType: "login",
      identityEmail: email,
      lookup: "login_email",
      outcome,
    });

    if (error instanceof Error && error.message === "mailbox-not-ready") {
      return Response.json(
        { error: "mailbox-not-ready", message: "메일함 준비가 완료된 뒤 앱에 로그인할 수 있습니다." },
        { status: 409, headers: NO_STORE_HEADERS },
      );
    }

    if (error instanceof Error && error.message.startsWith("mailcow-password-policy:")) {
      return Response.json(
        {
          error: "legacy-password-policy",
          message: "기존 앱 연결을 위해 계정 비밀번호를 메일 서버 보안 기준에 맞게 변경해야 합니다.",
        },
        { status: 409, headers: NO_STORE_HEADERS },
      );
    }

    if (error instanceof Error && error.message === "growth-plan-required") {
      return Response.json(
        {
          error: "growth-plan-required",
          message: "성장플랜부터 이용할 수 있어요!",
        },
        { status: 403, headers: NO_STORE_HEADERS },
      );
    }

    if (
      error instanceof Error &&
      (error.message === "invalid-password" || error.message === "required")
    ) {
      return invalidCredentialsResponse();
    }

    console.error("App login verification failed", error);
    return Response.json(
      {
        error: "system",
        message: "로그인을 확인하지 못했습니다. 잠시 후 다시 시도해주세요.",
      },
      { status: 500, headers: NO_STORE_HEADERS },
    );
  }
}
