export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    const path = url.pathname;

    // 1. Strip index.html from end of path
    if (path.endsWith("/index.html")) {
      url.pathname = path.slice(0, -10);
      return Response.redirect(url.toString(), 301);
    }

    // 2. Root or trailing slash - append index.html and return
    if (path.endsWith("/")) {
      url.pathname = path + "index.html";
      return fetch(new Request(url, request));
    }

    // 3. Try the original request
    const response = await fetch(request);

    if (response.status !== 404) {
      return response;
    }

    // 4. Got 404 - check if /index.html exists
    url.pathname = path + "/index.html";
    const indexResponse = await fetch(new Request(url, request));

    if (indexResponse.status !== 404) {
      // Redirect to trailing slash version
      url.pathname = path + "/";
      return Response.redirect(url.toString(), 301);
    }

    // Both 404 - return original 404
    return response;
  },
};
