"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var app_router_redirect_preview_exports = {};
__export(app_router_redirect_preview_exports, {
  appRouterRedirectPreviewHandler: () => appRouterRedirectPreviewHandler,
  originalRequestProtocol: () => originalRequestProtocol
});
module.exports = __toCommonJS(app_router_redirect_preview_exports);
var import_server = require("next/server");
var import_headers = require("next/headers");
var import_cookie = require("cookie");
var import_cookies = require("../../../api-handler/cookies");
var import_site_version = require("../../../api/site-version");
var import_preview = require("../preview");
function originalRequestProtocol(request) {
  const forwardedProto = request.headers.get("x-forwarded-proto");
  return forwardedProto != null ? forwardedProto.split(",")[0].trim() : null;
}
async function appRouterRedirectPreviewHandler(request, _context, client) {
  const previewToken = request.nextUrl.searchParams.get(import_preview.SearchParams.PreviewToken);
  if (previewToken == null) {
    return new import_server.NextResponse("Bad request: no preview token provided", { status: 400 });
  }
  const verificationResult = await client.readPreviewToken(previewToken);
  if (verificationResult == null) {
    return new import_server.NextResponse("Failed to verify preview token", { status: 401 });
  }
  const { payload } = verificationResult;
  const draft = await (0, import_headers.draftMode)();
  const cookieStore = await (0, import_headers.cookies)();
  draft.enable();
  const prerenderBypassCookie = cookieStore.get(import_preview.PRERENDER_BYPASS_COOKIE);
  if (prerenderBypassCookie?.value == null) {
    return new import_server.NextResponse("Could not retrieve draft mode bypass cookie", { status: 500 });
  }
  const siteVersion = { version: payload.version, token: previewToken };
  const serializedSiteVersion = (0, import_site_version.serializeSiteVersion)(siteVersion);
  const secondsUntilExpiration = (0, import_site_version.secondsUntilSiteVersionExpiration)(siteVersion);
  const draftCookies = [
    prerenderBypassCookie,
    { name: import_preview.MAKESWIFT_SITE_VERSION_COOKIE, value: serializedSiteVersion }
  ];
  const redirectProtocol = originalRequestProtocol(request) ?? request.nextUrl.protocol.replace(":", "");
  const redirectHost = request.headers.get("x-forwarded-host") ?? request.headers.get("host") ?? request.nextUrl.host;
  const redirectUrl = new URL(
    `${redirectProtocol}://${redirectHost}${request.nextUrl.pathname}${request.nextUrl.search}`
  );
  redirectUrl.searchParams.delete(import_preview.SearchParams.PreviewToken);
  redirectUrl.searchParams.delete(import_preview.RewriteRuleMatches.PreviewToken);
  redirectUrl.searchParams.delete(import_preview.RewriteRuleMatches.OriginalPath);
  const headers = new Headers();
  draftCookies.forEach(({ name, value }) => {
    headers.append(
      import_cookies.SET_COOKIE_HEADER,
      (0, import_cookie.serialize)(name, value, { ...import_cookies.cookieSettingOptions, maxAge: secondsUntilExpiration })
    );
  });
  return import_server.NextResponse.redirect(redirectUrl, { headers });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  appRouterRedirectPreviewHandler,
  originalRequestProtocol
});
//# sourceMappingURL=app-router-redirect-preview.js.map