import { redirect, type LoaderFunctionArgs } from "react-router";
import {
  getDashboardDetail,
  listDashboards,
} from "@/lib/features/dashboard/action";
import type { DashboardDetail } from "@/lib/features/dashboard/types";
import { createRoleProtectedLoader } from "@/lib/features/protectedFetcher";
import { FEATURE_SLUGS } from "@/lib/role-helpers";
import DashboardViewer from "./_client";

/**
 * Full-bleed authenticated viewer at /admin/dashboard/:slug/view.
 *
 * Registered as a sibling of console.layout rather than inside it, so the
 * sidebar and page chrome are absent and the dashboard gets the whole viewport.
 * The path still starts with /admin, so root.layout's auth gate applies.
 *
 * The loader only needs enough to build the iframe src and to bail out
 * gracefully — the serve proxy itself re-enforces access on every request, so
 * this is convenience, not the security boundary.
 */
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;

    // Same slug→id resolution as the management page: the list is fail-closed,
    // so a dashboard the viewer can't see simply isn't in it.
    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 = await getDashboardDetail(match.id, cookie);
    if (!detailRes?.success) throw redirect("/admin/dashboard");

    // Nothing to render without a published version — send them to management,
    // where they can upload or publish one.
    if (!detailRes.data.dashboard.current_version_id) {
      throw redirect(`/admin/dashboard/${slug}`);
    }
    return { detail: detailRes.data };
  },
);

const Page = ({ loaderData }: { loaderData: { detail: DashboardDetail } }) => (
  <DashboardViewer detail={loaderData.detail} />
);

export default Page;
