import axios from 'axios';

const BACKEND_SERVER_URL = process.env.BACKEND_SERVER_URL;
const BACKEND_SITE_NAME = process.env.BACKEND_SITE_NAME;

// 递归处理菜单层级，拼接完整 slug 路径
function buildMenuTree(items, parent = null, parentPath = "") {
  return items
    .filter(item => (item.parent_jsite_menu === parent || (!item.parent_jsite_menu && !parent)))
    .map(item => {
      // 拼接完整路径，保证以 / 开头
      let currentPath = parentPath ? `${parentPath}/${item.slug.replace(/^\//, "")}` : item.slug;
      if (!currentPath.startsWith('/')) currentPath = '/' + currentPath;
      return {
        id: item.name,
        label: item.title,
        href: currentPath,
        position: item.position,
        order: item.order,
        icon: item.icon,
        children: buildMenuTree(items, item.name, currentPath),
      };
    });
}

export async function GET(request) {
  try {
    const response = await axios.get(
      `${BACKEND_SERVER_URL}/api/action/jsite.api.v1.get_menu`,
      { params: { site_name: BACKEND_SITE_NAME } }
    );
    const items = response.data.message?.data || [];
    const menuTree = buildMenuTree(items);
    return Response.json({ menu: menuTree });
  } catch (error) {
    return Response.json(
      { error: error.message, detail: error?.response?.data || null },
      { status: 500 }
    );
  }
} 