import { Outlet } from "@remix-run/react";
import { redirect, type LoaderFunctionArgs, type MetaFunction } from "@remix-run/node";

export const meta: MetaFunction = () => {
  return [
    { title: "评查规则管理 - 中国烟草AI合同及卷宗审核系统" },
    {
      name: "rules",
      content: "评查规则管理模块，包括评查点列表、创建和编辑功能"
    }
  ];
};

export const handle = {
  breadcrumb: "评查点列表",
  to: "/rulesTest/list"  // 新版规则维护入口；旧版可从新版页面内返回
};

export async function loader({ request }: LoaderFunctionArgs) {
  const url = new URL(request.url);
  const { getUserSession } = await import("~/api/login/auth.server");
  const { frontendJWT, userInfo } = await getUserSession(request);
  const { requireRoutePermission } = await import("~/api/auth/check-route-permission.server");

  await requireRoutePermission("/rules", userInfo?.role || "", frontendJWT || undefined);

  if (url.pathname === '/rules') {
    const query = url.searchParams.toString();
    throw redirect(query ? `/rulesTest/list?${query}` : '/rulesTest/list');
  }

  return null;
}

/**
 * 规则管理路由布局
 */
export default function RulesLayout() {
  return <Outlet />;
}
