import { CustomerPageShell } from "@/app/customer/_components/customer-page-shell";
import { fetchPortalLinkBankCustomers } from "@/app/customer/_lib/admin/link-bank-accounts-server-api";
import { fetchPortalUnassignedBanks } from "@/app/customer/_lib/admin/parent-banks-server-api";
import {
  EMPTY_CUSTOMER_PORTAL_CAPABILITIES,
  getCustomerSessionContext,
} from "@/lib/frontend-auth/server";

import { UnassignedBanksPageClient } from "./_components/unassigned-banks-page-client";

type PageProps = {
  params: Promise<{ tenant: string }>;
};

export default async function UnassignedBanksAdminPage({ params }: Readonly<PageProps>) {
  const { tenant } = await params;
  const [unassignedResult, customersResult, session] = await Promise.all([
    fetchPortalUnassignedBanks(tenant),
    fetchPortalLinkBankCustomers(tenant),
    getCustomerSessionContext(tenant),
  ]);

  const capabilities = session.permissions.capabilities ?? EMPTY_CUSTOMER_PORTAL_CAPABILITIES;
  const canManage =
    capabilities.admin_link_bank_manage ||
    session.permissions.routes.includes("access/link_bank_accounts_manage") ||
    session.permissions.routes.includes("access/parent_banks_manage");

  return (
    <CustomerPageShell>
      <UnassignedBanksPageClient
        tenant={tenant}
        initialCustomers={customersResult.items}
        initialUnassignedAccounts={unassignedResult.unassignedAccounts}
        initialErrorMessage={unassignedResult.errorMessage ?? customersResult.errorMessage}
        canManage={canManage}
      />
    </CustomerPageShell>
  );
}
