"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { after } from "next/server";
import { logger } from "@/server/logger";
import { canEdit, VIEW_ONLY_ERROR } from "@/lib/auth/roles";
import { destroySession, getCurrentUser, requireUser } from "@/server/auth/session";
import { startManualRun } from "@/server/scheduler/run";

export async function logoutAction() {
  const user = await getCurrentUser();
  await destroySession();
  if (user) logger.info("auth.logout", { username: user.username });
  redirect("/login");
}

export type CheckAllResult = { ok: true } | { ok: false; error: string };

/**
 * "Check All": same engine and same lock as the scheduler. Returns as soon as
 * the run is claimed; the dashboard shows progress and refreshes itself while
 * the run is active.
 */
export async function checkAllAction(): Promise<CheckAllResult> {
  const user = await requireUser();
  if (!canEdit(user)) return { ok: false, error: VIEW_ONLY_ERROR };

  try {
    const run = await startManualRun(user.username);
    if (!run) return { ok: false, error: "A check run is already in progress." };

    logger.info("health.check_all.manual", { by: user.username });
    after(run.execute);
  } catch (error) {
    logger.error("health.check_all.failed", { error });
    return { ok: false, error: "Could not start the check run. Please try again." };
  }

  revalidatePath("/");
  revalidatePath("/apps");
  return { ok: true };
}
