"use server";

import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { requireDashboardContext } from "@/core/auth/dashboard-context";
import {
  requestEmailChangeSchema,
  updateAccountProfileSchema,
} from "@/core/validation/schemas";
import {
  AccountError,
  cancelEmailChange,
  requestEmailChange,
  resendEmailChange,
  updateAccountProfile,
} from "@/services/account-service";
import { writeAuditLog } from "@/services/audit-service";
import type { ActionResult } from "@/app/dashboard/actions";

async function requestHostFromHeaders(): Promise<string | null> {
  const h = await headers();
  return h.get("x-archi-hostname") ?? h.get("host") ?? null;
}

function mapAccountError(error: unknown): ActionResult {
  if (error instanceof AccountError) {
    return { ok: false, error: error.message };
  }
  const message =
    error instanceof Error ? error.message : "Account update failed";
  return { ok: false, error: message };
}

export async function updateAccountProfileAction(
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext();
    const parsed = updateAccountProfileSchema.safeParse({
      name: String(formData.get("name") ?? ""),
      phone: String(formData.get("phone") ?? ""),
    });
    if (!parsed.success) {
      return { ok: false, error: "Validation failed" };
    }

    await updateAccountProfile(ctx.user.id, parsed.data);
    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "account.profile.update",
      targetType: "user",
      targetId: ctx.user.id,
    });

    revalidatePath("/dashboard/settings");
    revalidatePath("/dashboard");
    return { ok: true };
  } catch (error) {
    return mapAccountError(error);
  }
}

export async function requestEmailChangeAction(
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext();
    const parsed = requestEmailChangeSchema.safeParse({
      newEmail: String(formData.get("newEmail") ?? ""),
      currentPassword: String(formData.get("currentPassword") ?? ""),
    });
    if (!parsed.success) {
      return { ok: false, error: "Validation failed" };
    }

    const requestHost = await requestHostFromHeaders();
    const result = await requestEmailChange(ctx.user.id, parsed.data, {
      requestHost,
    });

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "account.email.change_requested",
      targetType: "user",
      targetId: ctx.user.id,
      metadata: { pendingEmail: result.pendingEmail },
    });

    revalidatePath("/dashboard/settings");
    return { ok: true };
  } catch (error) {
    return mapAccountError(error);
  }
}

export async function resendEmailChangeAction(): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext();
    const requestHost = await requestHostFromHeaders();
    const result = await resendEmailChange(ctx.user.id, { requestHost });

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "account.email.change_resent",
      targetType: "user",
      targetId: ctx.user.id,
      metadata: { pendingEmail: result.pendingEmail },
    });

    revalidatePath("/dashboard/settings");
    return { ok: true };
  } catch (error) {
    return mapAccountError(error);
  }
}

export async function cancelEmailChangeAction(): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext();
    await cancelEmailChange(ctx.user.id);

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "account.email.change_cancelled",
      targetType: "user",
      targetId: ctx.user.id,
    });

    revalidatePath("/dashboard/settings");
    return { ok: true };
  } catch (error) {
    return mapAccountError(error);
  }
}
