import BreadCrumbLink from "@/layouts/shared/page.breadcrumbLink";
import { createRoleProtectedLoader } from "@/lib/features/protectedFetcher";
import { listEDMFolders, listEDMTemplates } from "@/lib/features/edm/query";
import type { EDMFolder, EDMTemplate } from "@/lib/features/edm/types";
import type { AccessScope, CoreResponse } from "@/lib/features/types";
import { FEATURE_SLUGS, getCheckedAccess, isDevInstance } from "@/lib/role-helpers";
import type { Route } from "./+types/page";
import EDMListClientPage from "./_client";

export const handle = {
  breadcrumb: () => (
    <BreadCrumbLink links={[{ label: "Email Templates" }, { label: "Overview" }]} />
  ),
};

export const loader = createRoleProtectedLoader(
  FEATURE_SLUGS.edm,
  "read",
  async ({ request }) => {
    const cookie = request.headers.get("Cookie") ?? "";
    // Folders are a small table and the list page always needs them for the
    // filter, so they ride along with the template fetch rather than costing a
    // second round trip after mount.
    const [response, foldersResponse] = await Promise.all([
      listEDMTemplates({ Cookie: cookie }),
      listEDMFolders({ Cookie: cookie }),
    ]);
    const accessScope = getCheckedAccess(request, FEATURE_SLUGS.edm);
    if (isDevInstance(request)) {
      accessScope.create = false;
      accessScope.update = false;
      accessScope.delete = false;
    }
    return { response, foldersResponse, accessScope };
  },
);

const EDMListPage: React.FC<Route.ComponentProps> = ({ loaderData }) => {
  const { response, foldersResponse, accessScope } = loaderData as unknown as {
    response: CoreResponse<EDMTemplate[]>;
    foldersResponse: CoreResponse<EDMFolder[]>;
    accessScope: AccessScope;
  };

  return (
    <EDMListClientPage
      initialTemplates={response?.success && Array.isArray(response.data) ? response.data : []}
      initialFolders={
        foldersResponse?.success && Array.isArray(foldersResponse.data)
          ? foldersResponse.data
          : []
      }
      initialError={response?.success ? undefined : response?.message}
      accessScope={accessScope}
    />
  );
};

export default EDMListPage;
