import { NextRequest, NextResponse } from "next/server";
import {
  buildWebManifest,
  PWA_VERSION,
  toPwaLang,
} from "@/lib/pwaConfig";
import {
  DEFAULT_LANGUAGE,
  isAppLanguage,
  LANGUAGE_COOKIE,
} from "@/lib/i18n/registry";
import { resolveLanguageFromAcceptHeader } from "@/lib/i18n/resolveLanguage";

export const dynamic = "force-dynamic";

function resolveLangFromRequest(request: NextRequest) {
  const queryLang = request.nextUrl.searchParams.get("lang");
  if (isAppLanguage(queryLang)) return queryLang;

  const cookieLang = request.cookies.get(LANGUAGE_COOKIE)?.value;
  if (isAppLanguage(cookieLang)) return cookieLang;

  const fromAccept = resolveLanguageFromAcceptHeader(
    request.headers.get("accept-language")
  );
  if (fromAccept) return fromAccept;

  return DEFAULT_LANGUAGE;
}

export async function GET(request: NextRequest) {
  const lang = toPwaLang(resolveLangFromRequest(request));
  const manifest = buildWebManifest(lang);

  return NextResponse.json(manifest, {
    headers: {
      "Content-Type": "application/manifest+json; charset=utf-8",
      "Cache-Control": "no-cache, no-store, must-revalidate",
      "X-PWA-Version": PWA_VERSION,
    },
  });
}
