import { adminHasAnyPermission } from "@/lib/admin-permissions";
import {
  PRD_AGENT_LINE_PROVISION,
  PRD_AGENTS_ACCESS_ANY,
  PRD_SETTLEMENT_AGENT_ACCESS_ANY,
} from "@/lib/admin-prd";
import type { AdminAgentContext } from "@/types/api/admin-agent";

type AdminSessionLike = {
  is_super_admin?: boolean;
  permissions?: string[] | null;
  agent?: AdminAgentContext | null;
};

/** 线路内绑定代理可查看账单；平台账号需 settlement.agent.* */
export function canAccessAgentSettlementBills(
  session: AdminSessionLike | null | undefined,
): boolean {
  if (session?.agent != null) {
    return true;
  }

  return adminHasAnyPermission(session?.permissions ?? [], [...PRD_SETTLEMENT_AGENT_ACCESS_ANY]);
}

/** 仅平台侧可开通新线路；绑定代理永不可见 */
export function canAccessAgentLineProvision(
  session: AdminSessionLike | null | undefined,
): boolean {
  if (session?.agent != null) {
    return false;
  }

  return adminHasAnyPermission(session?.permissions ?? [], [PRD_AGENT_LINE_PROVISION]);
}

export function isAgentLineSubnavTabVisible(
  href: string,
  session: AdminSessionLike | null | undefined,
): boolean {
  const perms = session?.permissions ?? [];
  const isSuper = session?.is_super_admin === true;

  if (isSuper) {
    return adminHasAnyPermission(perms, tabRequiredSlugs(href));
  }

  if (href === "/admin/agents/provision") {
    return canAccessAgentLineProvision(session);
  }

  if (href === "/admin/settlement-center" || href === "/admin/agents/settlement-bills") {
    return canAccessAgentSettlementBills(session);
  }

  if (href === "/admin/agents") {
    return adminHasAnyPermission(perms, [...PRD_AGENTS_ACCESS_ANY]);
  }

  return false;
}

function tabRequiredSlugs(href: string): readonly string[] {
  switch (href) {
    case "/admin/agents":
      return PRD_AGENTS_ACCESS_ANY;
    case "/admin/agents/provision":
      return [PRD_AGENT_LINE_PROVISION];
    case "/admin/settlement-center":
    case "/admin/agents/settlement-bills":
      return PRD_SETTLEMENT_AGENT_ACCESS_ANY;
    default:
      return [];
  }
}
