import { redirect, type LoaderFunctionArgs } from "react-router";
import BreadCrumbLink from "@/layouts/shared/page.breadcrumbLink";
import { createRoleProtectedLoader } from "@/lib/features/protectedFetcher";
import {
  getDashboardAudit,
  getDashboardDetail,
  listDashboards,
} from "@/lib/features/dashboard/action";
import type {
  DashboardAuditEntry,
  DashboardDetail,
} from "@/lib/features/dashboard/types";
import { FEATURE_SLUGS } from "@/lib/role-helpers";
import DashboardManagePage from "./_client";

export const handle = {
  breadcrumb: () => (
    <BreadCrumbLink
      links={[{ label: "Dashboards", to: "/admin/dashboard" }, { label: "Manage" }]}
    />
  ),
};

/**
 * Unlike the listing, this route CAN use the role-protected loader: it is not
 * the fallback landing route, so bouncing an unauthorised visitor back to
 * /admin/dashboard is the right behaviour.
 *
 * The URL carries a slug (prompt 5 wired the cards that way) while the API is
 * keyed by id, so the slug is resolved against the already-scoped list rather
 * than by adding a slug lookup to the backend. The list is fail-closed, so a
 * slug the viewer can't see simply isn't in it and they get bounced.
 */
export const loader = createRoleProtectedLoader(
  FEATURE_SLUGS.dashboard,
  "read",
  async ({ params, request }: LoaderFunctionArgs) => {
    const cookie = { Cookie: request.headers.get("Cookie") ?? "" };
    const slug = params.slug as string;

    const list = await listDashboards(cookie);
    const match = list?.success
      ? (list.data ?? []).find((d) => d.slug === slug)
      : undefined;
    if (!match) throw redirect("/admin/dashboard");

    const [detailRes, auditRes] = await Promise.all([
      getDashboardDetail(match.id, cookie),
      // 403s for non-admins; an empty timeline is the right fallback, not an error.
      getDashboardAudit(match.id, cookie),
    ]);
    if (!detailRes?.success) throw redirect("/admin/dashboard");

    return {
      detail: detailRes.data,
      audit: auditRes?.success ? (auditRes.data ?? []) : [],
    };
  },
);

const Page = ({
  loaderData,
}: {
  loaderData: { detail: DashboardDetail; audit: DashboardAuditEntry[] };
}) => {
  const { detail, audit } = loaderData;
  return <DashboardManagePage detail={{ ...detail, audit }} />;
};

export default Page;
