"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { after } from "next/server";
import {
  domainFormValues,
  validateDomain,
  type DomainFieldErrors,
  type DomainFormValues,
} from "@/lib/validation/domain";
import { canEdit, VIEW_ONLY_ERROR } from "@/lib/auth/roles";
import { requireUser } from "@/server/auth/session";
import { startManualDomainRun } from "@/server/domains/run";
import {
  DomainNotFoundError,
  DuplicateDomainError,
  addDomain,
  checkDomain,
  removeDomain,
  restoreDomain,
  updateDomain,
} from "@/server/domains/service";
import { logger } from "@/server/logger";

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

export type DomainFormState = {
  values?: DomainFormValues;
  fieldErrors?: DomainFieldErrors;
  error?: string;
};

function revalidateDomainViews() {
  revalidatePath("/domains");
  revalidatePath("/");
}

/** "Check Domains Now": same run and same lock as the daily check; returns once the run is claimed. */
export async function checkDomainsAction(): Promise<DomainActionResult> {
  const user = await requireUser();
  if (!canEdit(user)) return { ok: false, error: VIEW_ONLY_ERROR };

  try {
    const run = await startManualDomainRun(user.username);
    if (!run) return { ok: false, error: "A domain check is already in progress." };
    logger.info("domain.run.manual", { by: user.username });
    // The Domains page polls while the run is active (RunInProgress), so it picks up results as they land.
    after(() => run.execute());
  } catch (error) {
    logger.error("domain.run.manual_failed", { error });
    return { ok: false, error: "The domain check could not be started. Please try again." };
  }

  revalidateDomainViews();
  return { ok: true };
}

/** Add Domain: watch a domain no app uses. Looked up straight away, then daily with the rest. */
export async function createDomainAction(_prev: DomainFormState, formData: FormData): Promise<DomainFormState> {
  const user = await requireUser();
  if (!canEdit(user)) return { error: VIEW_ONLY_ERROR };
  const values = domainFormValues(formData);

  const validated = validateDomain(values, { requireName: true });
  if (!validated.ok) return { values, fieldErrors: validated.fieldErrors };

  try {
    const { domain, needsLookup } = await addDomain(validated.data);
    logger.info("domain.added", { domain: domain.name, by: user.username });
    if (needsLookup) {
      after(() => checkDomain(domain.name).catch((error) => logger.error("domain.lookup.errored", { domain: domain.name, error })));
    }
  } catch (error) {
    if (error instanceof DuplicateDomainError) {
      return { values, fieldErrors: { name: `${validated.data.name} is already listed` } };
    }
    logger.error("domain.add.failed", { error });
    return { values, error: "Something went wrong while saving. Please try again." };
  }

  revalidateDomainViews();
  redirect("/domains");
}

/** Edit Domain: registrar and the hand-entered expiry date. */
export async function updateDomainAction(id: string, _prev: DomainFormState, formData: FormData): Promise<DomainFormState> {
  const user = await requireUser();
  if (!canEdit(user)) return { error: VIEW_ONLY_ERROR };
  const values = domainFormValues(formData);

  const validated = validateDomain(values, { requireName: false });
  if (!validated.ok) return { values, fieldErrors: validated.fieldErrors };

  try {
    await updateDomain(id, validated.data);
    logger.info("domain.updated", { domainId: id, by: user.username });
  } catch (error) {
    if (error instanceof DomainNotFoundError) return { values, error: "This domain no longer exists. It may have been deleted." };
    logger.error("domain.update.failed", { domainId: id, error });
    return { values, error: "Something went wrong while saving. Please try again." };
  }

  revalidateDomainViews();
  redirect("/domains");
}

export type DeleteDomainResult = { ok: true; outcome: "hidden" | "deleted" } | { ok: false; error: string };

/** Delete: removes a domain added by hand; hides (restorably) one an app still uses. */
export async function deleteDomainAction(id: string): Promise<DeleteDomainResult> {
  const user = await requireUser();
  if (!canEdit(user)) return { ok: false, error: VIEW_ONLY_ERROR };
  if (typeof id !== "string") return { ok: false, error: "Invalid request." };

  try {
    const outcome = await removeDomain(id);
    logger.info(outcome === "hidden" ? "domain.hidden" : "domain.deleted", { domainId: id, by: user.username });
    revalidateDomainViews();
    return { ok: true, outcome };
  } catch (error) {
    // Already gone is the outcome the user wanted.
    if (error instanceof DomainNotFoundError) {
      revalidateDomainViews();
      return { ok: true, outcome: "deleted" };
    }
    logger.error("domain.delete.failed", { domainId: id, error });
    return { ok: false, error: "Could not delete the domain. Please try again." };
  }
}

export async function restoreDomainAction(id: string): Promise<DomainActionResult> {
  const user = await requireUser();
  if (!canEdit(user)) return { ok: false, error: VIEW_ONLY_ERROR };
  if (typeof id !== "string") return { ok: false, error: "Invalid request." };

  try {
    await restoreDomain(id);
    logger.info("domain.restored", { domainId: id, by: user.username });
  } catch (error) {
    if (error instanceof DomainNotFoundError) return { ok: false, error: "This domain no longer exists." };
    logger.error("domain.restore.failed", { domainId: id, error });
    return { ok: false, error: "Could not restore the domain. Please try again." };
  }

  revalidateDomainViews();
  return { ok: true };
}
