import { NextRequest, NextResponse } from "next/server";

import { DEFAULT_LOCALE, isLocale, LOCALE_COOKIE } from "@/lib/i18n";

function sanitizeLocale(raw: string | null) {
  if (isLocale(raw)) {
    return raw;
  }

  return DEFAULT_LOCALE;
}

export async function GET(request: NextRequest) {
  const rawTo = request.nextUrl.searchParams.get("to");
  const nextLocale = sanitizeLocale(rawTo);
  const back = request.headers.get("referer") || "/";
  const destination = new URL(back, request.url);

  const response = NextResponse.redirect(destination);
  response.cookies.set(LOCALE_COOKIE, nextLocale, {
    path: "/",
    secure: process.env.NODE_ENV === "production",
    maxAge: 365 * 24 * 60 * 60,
    sameSite: "lax"
  });

  return response;
}
