<script setup lang="ts">
const route = useRoute();
const config = useRuntimeConfig();
const localePath = useLocalePath();
const { availableLocales } = useI18n();

interface UTMResponse {
  success: boolean;
  data?: { redirect_url?: string } | null;
  message?: string | null;
}

function getMsg(err: unknown): string | null {
  const e = err as { message?: unknown; data?: { message?: unknown } } | null;
  if (e?.data?.message && typeof e.data.message === "string")
    return e.data.message;
  if (e?.message && typeof e.message === "string") return e.message;
  return null;
}

const code = Array.isArray(route.params.code)
  ? route.params.code[0]
  : (route.params.code as string | undefined);

const { data, error } = await useFetch<UTMResponse>(
  `${config.public.apiBase}utm`,
  {
    method: "POST",
    body: { shorten_code: code },
  },
);

if (error.value) {
  const msg = getMsg(error.value) || "Campaign not found";
  throw createError({ statusCode: 404, statusMessage: msg });
}

const res = data.value;
const redirectUrl = res?.data?.redirect_url?.trim();
if (!res?.success || !redirectUrl) {
  const msg =
    (res && typeof res.message === "string" && res.message) ||
    "Campaign not found";
  throw createError({ statusCode: 404, statusMessage: msg });
}

// Ensure navigation stays internal to the app and prevent going back
let targetPath = redirectUrl;
if (!redirectUrl.startsWith("/")) {
  try {
    const u = new URL(redirectUrl);
    targetPath = `${u.pathname}${u.search}${u.hash}` || "/";
  } catch {
    // If it's not a valid absolute URL, fallback to treating it as a path
    targetPath = redirectUrl.startsWith("/") ? redirectUrl : `/${redirectUrl}`;
  }
}
// Normalize leading slash
if (!targetPath.startsWith("/")) targetPath = `/${targetPath}`;

// Apply i18n localization if path is not already prefixed with a supported locale
const hasLocalePrefix = Array.isArray(availableLocales)
  ? availableLocales.some(
      (code) =>
        targetPath === `/${code}` ||
        targetPath.startsWith(`/${code}/`) ||
        targetPath.startsWith(`/${code}?`),
    )
  : false;

const finalPath = hasLocalePrefix ? targetPath : localePath(targetPath);

await navigateTo(finalPath, { replace: true });
</script>
