"use server";

import { headers } from "next/headers";
import {
  AuthenticationError,
  AuthorizationError,
  OperationNotAllowedError,
  TooManyRequestsError,
} from "@formbricks/types/errors";
import {
  TUserPersonalInfoUpdateInput,
  TUserUpdateInput,
  ZUserPersonalInfoUpdateInput,
} from "@formbricks/types/user";
import { getIsEmailUnique } from "@/app/(app)/workspaces/[workspaceId]/settings/account/profile/lib/user";
import { EMAIL_VERIFICATION_DISABLED, PASSWORD_RESET_DISABLED, WEBAPP_URL } from "@/lib/constants";
import { verifyUserPassword } from "@/lib/user/password";
import { getUser, updateUser } from "@/lib/user/service";
import { authenticatedActionClient } from "@/lib/utils/action-client";
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
import { auth } from "@/modules/auth/lib/auth";
import { updateBrevoCustomer } from "@/modules/auth/lib/brevo";
import { applyRateLimit } from "@/modules/core/rate-limit/helpers";
import { rateLimitConfigs } from "@/modules/core/rate-limit/rate-limit-configs";
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
import { sendVerificationNewEmail } from "@/modules/email";

function buildUserUpdatePayload(parsedInput: TUserPersonalInfoUpdateInput): TUserUpdateInput {
  return {
    ...(parsedInput.name && { name: parsedInput.name }),
    ...(parsedInput.locale && { locale: parsedInput.locale }),
  };
}

/**
 * Refuse a name change for an SSO user, mirroring the identical guard `handleEmailUpdate` applies to
 * the address.
 *
 * The identity provider owns `User.name` — it is re-read on every sign-in (`overrideUserInfo` in
 * modules/ee/sso/lib/better-auth-providers.ts) — so `EditProfileDetailsForm` renders the input
 * disabled. That is presentation, not enforcement: this action takes `name` straight off the request,
 * so a crafted call would still land a write that sticks until the user's next sign-in silently
 * reverts it. Enforce it at the boundary instead.
 *
 * Only a *differing* name is rejected. The form omits untouched fields, but a client that echoes the
 * current value back is asking for no change, and erroring on that would be a false positive.
 */
function assertNameUpdateAllowed({
  ctx,
  parsedInput,
}: {
  ctx: AuthenticatedActionClientCtx;
  parsedInput: TUserPersonalInfoUpdateInput;
}): void {
  const inputName = parsedInput.name?.trim();
  if (!inputName || inputName === ctx.user.name) return;

  if (ctx.user.identityProvider !== "email") {
    throw new OperationNotAllowedError("Name update is not allowed for non-credential users.");
  }
}

async function handleEmailUpdate({
  ctx,
  parsedInput,
  payload,
}: {
  ctx: AuthenticatedActionClientCtx;
  parsedInput: TUserPersonalInfoUpdateInput;
  payload: TUserUpdateInput;
}) {
  const inputEmail = parsedInput.email?.trim().toLowerCase();
  if (!inputEmail || ctx.user.email === inputEmail) return payload;

  await applyRateLimit(rateLimitConfigs.actions.emailUpdate, ctx.user.id);

  if (ctx.user.identityProvider !== "email") {
    throw new OperationNotAllowedError("Email update is not allowed for non-credential users.");
  }
  if (!parsedInput.password) {
    throw new AuthenticationError("Password is required to update email.");
  }
  const isCorrectPassword = await verifyUserPassword(ctx.user.id, parsedInput.password);
  if (!isCorrectPassword) {
    throw new AuthorizationError("Incorrect credentials");
  }
  const isEmailUnique = await getIsEmailUnique(inputEmail);
  if (!isEmailUnique) return payload;

  if (EMAIL_VERIFICATION_DISABLED) {
    payload.email = inputEmail;
    await updateBrevoCustomer({ id: ctx.user.id, email: inputEmail });
  } else {
    try {
      await sendVerificationNewEmail(ctx.user.id, inputEmail, ctx.user.locale);
    } catch (error) {
      // A taken address returns quietly above, so a capped email (ENG-3823) must too, or the refusal would
      // tell the user which addresses are free.
      if (!(error instanceof TooManyRequestsError)) throw error;
    }
  }
  return payload;
}

export const updateUserAction = authenticatedActionClient.inputSchema(ZUserPersonalInfoUpdateInput).action(
  withAuditLogging("updated", "user", async ({ ctx, parsedInput }) => {
    const oldObject = await getUser(ctx.user.id);
    assertNameUpdateAllowed({ ctx, parsedInput });
    let payload = buildUserUpdatePayload(parsedInput);
    payload = await handleEmailUpdate({ ctx, parsedInput, payload });

    // Only proceed with updateUser if we have actual changes to make
    let newObject = oldObject;
    if (Object.keys(payload).length > 0) {
      newObject = await updateUser(ctx.user.id, payload);
    }

    ctx.auditLoggingCtx.userId = ctx.user.id;
    ctx.auditLoggingCtx.oldObject = oldObject;
    ctx.auditLoggingCtx.newObject = newObject;

    return true;
  })
);

export const resetPasswordAction = authenticatedActionClient.action(
  withAuditLogging("passwordReset", "user", async ({ ctx }) => {
    if (PASSWORD_RESET_DISABLED) {
      throw new OperationNotAllowedError("Password reset is disabled");
    }

    if (ctx.user.identityProvider !== "email") {
      throw new OperationNotAllowedError("Password reset is not allowed for this user.");
    }

    // Without a limit this was the one way to have reset emails sent unbounded. A budget of its own, so
    // strangers spending forgot-password's per-account budget cannot lock the user out of this one.
    await applyRateLimit(rateLimitConfigs.actions.passwordResetRequest, ctx.user.id);

    await auth.api.requestPasswordReset({
      body: { email: ctx.user.email, redirectTo: `${WEBAPP_URL}/auth/forgot-password/reset` },
      headers: await headers(),
    });

    ctx.auditLoggingCtx.userId = ctx.user.id;

    return { success: true };
  })
);
