import { defineEventHandler, getQuery } from "h3";
import { withQuery } from "ufo";
import { getPathRobotConfig } from "../../composables/getPathRobotConfig.js";
export default defineEventHandler(async (e) => {
  const query = getQuery(e);
  const path = query.path;
  const isMockProduction = Boolean(query.mockProductionEnv);
  delete query.path;
  let robotsHeader = null;
  let robotsContent = null;
  let robotsHint = null;
  const res = await $fetch.raw(withQuery(path, query)).catch(() => null);
  if (res) {
    const html = res._data;
    robotsHeader = String(res.headers.get("x-robots-tag"));
    if (isMockProduction) {
      const productionHeader = res.headers.get("x-robots-production");
      if (productionHeader) {
        robotsHeader = String(productionHeader);
      }
      const productionMeta = String(html).match(/<meta[^>]+name=["']robots["'][^>]+data-production-content=["']([^"']+)["'](?:[^>]+data-hint=["']([^"']+)["'])?[^>]*>/i);
      if (productionMeta) {
        [, robotsContent = null, robotsHint = null] = productionMeta;
      }
    }
    if (!robotsContent) {
      const robotsMeta = String(html).match(/<meta[^>]+name=["']robots["'][^>]+content=["']([^"']+)["'](?:[^>]+data-hint=["']([^"']+)["'])?[^>]*>/i);
      if (robotsMeta) {
        [, robotsContent = null, robotsHint = null] = robotsMeta;
      }
    }
  }
  if (!robotsContent) {
    const robotConfig = getPathRobotConfig(e, {
      path,
      skipSiteIndexable: isMockProduction
    });
    robotsContent = robotConfig.rule;
    robotsHint = robotConfig.debug?.source || null;
    if (!robotsHeader) {
      robotsHeader = robotConfig.rule;
    }
  }
  const [source, line] = robotsHint ? robotsHint.split(",") : [null, null];
  return {
    rule: robotsContent,
    indexable: !(robotsContent?.includes("noindex") || robotsHeader?.includes("noindex")),
    crawlable: !(source === "/robots.txt"),
    path,
    debug: {
      source,
      line
    },
    robotsHeader,
    robotsContent
  };
});
