"use client";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import { liveDashboardQueryKeys } from "@/features/cdc-gpsf/dashboard/hook/use-cdc-gpsf-dashboard";

import {
  generateDraftDashboard,
  getDraftDashboard,
  publishLiveDashboard,
  type DraftDashboardBoard,
  type DraftDashboardStage,
} from "./draft-dashboard-service";

export const draftDashboardQueryKeys = {
  all: ["cdc-gpsf-draft-dashboard"] as const,
  // The board and the stage are part of the key, so the four dashboard pages
  // keep their own cached numbers.
  detail: (
    progressReportId: number,
    stage: DraftDashboardStage,
    board: DraftDashboardBoard = "pswg",
  ) =>
    [...draftDashboardQueryKeys.all, board, stage, progressReportId] as const,
};

// Loads the PSWG draft dashboard of one progress report. The id comes from
// the URL, so it is a string and has to be checked before it is used.
export function useDraftDashboard(
  id: string,
  stage: DraftDashboardStage = "draft",
  board: DraftDashboardBoard = "pswg",
) {
  const progressReportId = Number(id);
  const isValidId = Number.isInteger(progressReportId) && progressReportId > 0;

  const query = useQuery({
    queryKey: draftDashboardQueryKeys.detail(progressReportId, stage, board),
    queryFn: () => getDraftDashboard(progressReportId, stage, board),
    enabled: isValidId,
  });

  return {
    dashboard: query.data ?? null,
    isValidId,
    isLoading: isValidId && query.isLoading,
    error:
      query.error instanceof Error
        ? query.error.message
        : query.error
          ? "Unable to load the draft dashboard."
          : null,
  };
}

// "Generate Draft Dashboard → PSWG". After a successful generate the saved
// numbers are reloaded, so the page always shows what was just written.
export function useGenerateDraftDashboard(
  stage: DraftDashboardStage = "draft",
  board: DraftDashboardBoard = "pswg",
) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (progressReportId: number) =>
      generateDraftDashboard(progressReportId, stage, board),
    onSuccess: async (_data, progressReportId) => {
      await queryClient.invalidateQueries({
        queryKey: draftDashboardQueryKeys.detail(progressReportId, stage, board),
      });
    },
  });
}

// "Live": publishes the final dashboard for every role. The live dashboard
// query is dropped afterwards, so those pages pick up the new numbers.
export function usePublishLiveDashboard(
  board: DraftDashboardBoard = "pswg",
) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (progressReportId: number) =>
      publishLiveDashboard(progressReportId, board),
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: liveDashboardQueryKeys.all,
      });
    },
  });
}
