import { defineMiddleware, sequence } from "astro:middleware";
import { middleware } from "astro:i18n"; // Astro's own i18n routing config

const langs = ["en", "de", "cs", "fr"]

export const userMiddleware = defineMiddleware(async (ctx, next) => {
  // this response might come from Astro's i18n middleware, and it might return a 404
  const response = await next();
  
  const exceptions = ["/api", "/public"]

  // If path is in exceptions (i.e. api or public) return default middleware to handle it
  if (exceptions.includes(ctx.url.pathname) ) {
    return response

  // If no lang is set => set to english (some pages are language-les exceptions)
  } else if ( !langs.some(item => ctx.url.href.includes(item)) ) {
	return Response.redirect(`${ctx.url.protocol}${ctx.url.host}/en${ctx.url.pathname}`);
  
  } else {
    return response;
  }
});

export const onRequest = sequence(
  userMiddleware,
  middleware({
    redirectToDefaultLocale: false,
    prefixDefaultLocale: true,
  })
);
