import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
  ResourceNotFoundError,
  SSO_RECOVERY_LINK_EXPIRED_ERROR_CODE,
  TooManyRequestsError,
} from "@formbricks/types/errors";
import { auth } from "@/modules/auth/lib/auth";
import { getUserByEmail } from "@/modules/auth/lib/user";
// Import mocked functions
import { applyIPRateLimit, applyRateLimit } from "@/modules/core/rate-limit/helpers";
import { rateLimitConfigs } from "@/modules/core/rate-limit/rate-limit-configs";
import { sendVerificationEmail } from "@/modules/email";
import { resendVerificationEmailAction } from "./actions";

// Mock dependencies
vi.mock("@/modules/core/rate-limit/helpers", () => ({
  applyIPRateLimit: vi.fn(),
  applyRateLimit: vi.fn(),
}));

vi.mock("@/modules/core/rate-limit/rate-limit-configs", () => ({
  rateLimitConfigs: {
    auth: {
      verifyEmail: { interval: 3600, allowedPerInterval: 10, namespace: "auth:verify" },
      verifyEmailPerAccount: { interval: 3600, allowedPerInterval: 3, namespace: "auth:verify:account" },
    },
  },
}));

vi.mock("@/modules/auth/lib/user", () => ({
  getUserByEmail: vi.fn(),
}));

vi.mock("@/modules/email", () => ({
  sendVerificationEmail: vi.fn(),
}));

// Email verification resends now go through Better Auth's native endpoint (ENG-1054).
vi.mock("@/modules/auth/lib/auth", () => ({
  auth: { api: { sendVerificationEmail: vi.fn() } },
}));

const cookieMocks = vi.hoisted(() => ({
  get: vi.fn(),
  set: vi.fn(),
}));

vi.mock("next/headers", () => ({
  headers: vi.fn(() => Promise.resolve(new Headers())),
  cookies: vi.fn(() => Promise.resolve(cookieMocks)),
}));

// The intent-cookie refresh (ENG-2562): classify/mint are unit-tested in signup-intent.test.ts; here
// only the action's decision — refresh iff the browser already proves this user — is under test.
const signupIntentMocks = vi.hoisted(() => ({
  classifySignupIntent: vi.fn(),
  createSignupIntentToken: vi.fn(),
}));

const recoveryIntentMocks = vi.hoisted(() => ({
  readSsoRecoveryIntent: vi.fn(),
  refreshSsoRecoveryIntent: vi.fn(),
  getSsoRecoveryPairedTtlSeconds: vi.fn(() => 60 * 15),
}));

vi.mock("@/modules/auth/lib/signup-intent", () => ({
  SIGNUP_INTENT_COOKIE_NAME: "formbricks.signup_intent",
  SIGNUP_INTENT_COOKIE_OPTIONS: { httpOnly: true, secure: false, path: "/", sameSite: "lax", maxAge: 3600 },
  classifySignupIntent: signupIntentMocks.classifySignupIntent,
  createSignupIntentToken: signupIntentMocks.createSignupIntentToken,
}));

vi.mock("@/modules/ee/sso/lib/recovery-intent", () => ({
  readSsoRecoveryIntent: recoveryIntentMocks.readSsoRecoveryIntent,
  refreshSsoRecoveryIntent: recoveryIntentMocks.refreshSsoRecoveryIntent,
  getSsoRecoveryPairedTtlSeconds: recoveryIntentMocks.getSsoRecoveryPairedTtlSeconds,
}));

vi.mock("@/lib/constants", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@/lib/constants")>();
  return {
    ...actual,
    WEBAPP_URL: "http://localhost:3000",
  };
});

vi.mock("@/modules/ee/audit-logs/lib/handler", () => ({
  withAuditLogging: vi.fn(<T>(_type: string, _object: string, fn: T) => fn),
}));

vi.mock("@/lib/utils/action-client", () => ({
  actionClient: {
    inputSchema: vi.fn().mockReturnThis(),
    action: vi.fn((fn) => fn),
  },
}));

describe("resendVerificationEmailAction", () => {
  const validInput = {
    email: "test@example.com",
  };

  const mockUser = {
    id: "user123",
    email: "test@example.com",
    locale: "en-US",
  };

  const mockVerifiedUser = {
    id: "user123",
    email: "test@example.com",
    emailVerified: true, // boolean post-cutover (ENG-1054); keep fixtures off the legacy Date contract
    name: "Test User",
  };

  const mockCtx = {
    auditLoggingCtx: {
      organizationId: "",
      userId: "",
    },
  };

  beforeEach(() => {
    vi.resetAllMocks();
    // Default: no stored intent, so a client-supplied recovery callback proves nothing on its own.
    recoveryIntentMocks.readSsoRecoveryIntent.mockResolvedValue(null);
    cookieMocks.get.mockReturnValue(undefined);
    signupIntentMocks.classifySignupIntent.mockReturnValue("absent");
    signupIntentMocks.createSignupIntentToken.mockReturnValue("fresh-intent-token");
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  describe("Rate Limiting", () => {
    test("should apply rate limiting before processing verification email resend", async () => {
      vi.mocked(getUserByEmail, { partial: true, deep: true }).mockResolvedValue(mockUser);

      await resendVerificationEmailAction({
        ctx: mockCtx,
        parsedInput: validInput,
      } as unknown as Parameters<typeof resendVerificationEmailAction>[0]);

      expect(applyIPRateLimit).toHaveBeenCalledWith(rateLimitConfigs.auth.verifyEmail);
      expect(applyIPRateLimit).toHaveBeenCalledBefore(vi.mocked(getUserByEmail));
    });

    test("should throw rate limit error when limit exceeded", async () => {
      vi.mocked(applyIPRateLimit).mockRejectedValue(
        new Error("Maximum number of requests reached. Please try again later.")
      );

      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: validInput,
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow("Maximum number of requests reached. Please try again later.");

      expect(getUserByEmail).not.toHaveBeenCalled();
      expect(sendVerificationEmail).not.toHaveBeenCalled();
    });

    test("should use correct rate limit configuration", async () => {
      vi.mocked(getUserByEmail, { partial: true, deep: true }).mockResolvedValue(mockUser);

      await resendVerificationEmailAction({
        ctx: mockCtx,
        parsedInput: validInput,
      } as unknown as Parameters<typeof resendVerificationEmailAction>[0]);

      expect(applyIPRateLimit).toHaveBeenCalledWith({
        interval: 3600,
        allowedPerInterval: 10,
        namespace: "auth:verify",
      });
    });

    // Anyone can ask for an account's verification email, so it is counted per account too: strangers on
    // many IPs must not spend the recipient's whole cap and leave the user's own resend with none (ENG-3823).
    test("counts each resend against the account", async () => {
      vi.mocked(getUserByEmail, { partial: true, deep: true }).mockResolvedValue(mockUser);

      await resendVerificationEmailAction({ ctx: mockCtx, parsedInput: validInput } as unknown as Parameters<
        typeof resendVerificationEmailAction
      >[0]);

      expect(applyRateLimit).toHaveBeenCalledWith(rateLimitConfigs.auth.verifyEmailPerAccount, mockUser.id);
    });

    test("sends nothing once the account's resends are spent", async () => {
      vi.mocked(getUserByEmail, { partial: true }).mockResolvedValue(mockUser);
      vi.mocked(applyRateLimit).mockRejectedValue(
        new Error("Maximum number of requests reached. Please try again later.")
      );

      await expect(
        resendVerificationEmailAction({ ctx: mockCtx, parsedInput: validInput } as unknown as Parameters<
          typeof resendVerificationEmailAction
        >[0])
      ).rejects.toThrow("Maximum number of requests reached. Please try again later.");

      expect(auth.api.sendVerificationEmail).not.toHaveBeenCalled();
      expect(sendVerificationEmail).not.toHaveBeenCalled();
    });

    // A spent cap must look like a sent email: only unverified accounts reach it, so an error here would
    // tell anyone which addresses have one (ENG-3823).
    test("answers success once the account's resends are spent, so it reveals nothing", async () => {
      vi.mocked(getUserByEmail, { partial: true }).mockResolvedValue(mockUser);
      vi.mocked(applyRateLimit).mockRejectedValue(
        new TooManyRequestsError("Maximum number of requests reached")
      );

      await expect(
        resendVerificationEmailAction({ ctx: mockCtx, parsedInput: validInput } as unknown as Parameters<
          typeof resendVerificationEmailAction
        >[0])
      ).resolves.toEqual({ success: true });

      expect(auth.api.sendVerificationEmail).not.toHaveBeenCalled();
      expect(sendVerificationEmail).not.toHaveBeenCalled();
    });

    test("should apply rate limiting even when user doesn't exist", async () => {
      vi.mocked(getUserByEmail).mockResolvedValue(null);

      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: validInput,
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow(ResourceNotFoundError);

      expect(applyIPRateLimit).toHaveBeenCalledWith(rateLimitConfigs.auth.verifyEmail);
    });
  });

  describe("Verification Email Resend Flow", () => {
    test("should send verification email when user exists and email is not verified", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail, { partial: true, deep: true }).mockResolvedValue(mockUser);

      const result = await resendVerificationEmailAction({
        ctx: mockCtx,
        parsedInput: validInput,
      } as unknown as Parameters<typeof resendVerificationEmailAction>[0]);

      expect(applyIPRateLimit).toHaveBeenCalled();
      expect(getUserByEmail).toHaveBeenCalledWith(validInput.email);
      expect(auth.api.sendVerificationEmail).toHaveBeenCalledWith({
        body: { email: mockUser.email, callbackURL: undefined },
        headers: expect.any(Headers),
      });
      expect(sendVerificationEmail).not.toHaveBeenCalled();
      expect(result).toEqual({ success: true });
    });

    test("should preserve a valid callback URL when resending the verification email", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail, { partial: true, deep: true }).mockResolvedValue(mockUser);

      await resendVerificationEmailAction({
        ctx: mockCtx,
        parsedInput: {
          ...validInput,
          callbackUrl: "http://localhost:3000/invite?token=invite-token",
        },
      } as unknown as Parameters<typeof resendVerificationEmailAction>[0]);

      expect(auth.api.sendVerificationEmail).toHaveBeenCalledWith({
        body: { email: mockUser.email, callbackURL: "http://localhost:3000/invite?token=invite-token" },
        headers: expect.any(Headers),
      });
    });

    test("should discard invalid callback URLs when resending the verification email", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail, { partial: true, deep: true }).mockResolvedValue(mockUser);

      await resendVerificationEmailAction({
        ctx: mockCtx,
        parsedInput: {
          ...validInput,
          callbackUrl: "https://evil.example/phish",
        },
      } as unknown as Parameters<typeof resendVerificationEmailAction>[0]);

      expect(auth.api.sendVerificationEmail).toHaveBeenCalledWith({
        body: { email: mockUser.email, callbackURL: undefined },
        headers: expect.any(Headers),
      });
    });

    test("should return success without sending email when user email is already verified", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail, { partial: true, deep: true }).mockResolvedValue(mockVerifiedUser);

      const result = await resendVerificationEmailAction({
        ctx: mockCtx,
        parsedInput: validInput,
      } as unknown as Parameters<typeof resendVerificationEmailAction>[0]);

      expect(applyIPRateLimit).toHaveBeenCalled();
      expect(getUserByEmail).toHaveBeenCalledWith(validInput.email);
      expect(sendVerificationEmail).not.toHaveBeenCalled();
      expect(result).toEqual({ success: true });
      // Nothing was sent, so strangers cannot use this to spend the account's resends (ENG-3823).
      expect(applyRateLimit).not.toHaveBeenCalled();
    });

    test("should resend an SSO recovery email for a verified user", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      const verifiedUserWithLocale: NonNullable<Awaited<ReturnType<typeof getUserByEmail>>> = {
        ...mockVerifiedUser,
        emailVerified: true,
        locale: "en-US",
        identityProvider: "email",
        isActive: true,
      };
      vi.mocked(getUserByEmail).mockResolvedValue(verifiedUserWithLocale);
      recoveryIntentMocks.readSsoRecoveryIntent.mockResolvedValue({
        callbackUrl: "http://localhost:3000",
        email: mockVerifiedUser.email,
        provider: "google",
        providerAccountId: "provider_123",
        userId: mockVerifiedUser.id,
        createdAt: Date.now(),
      });
      recoveryIntentMocks.getSsoRecoveryPairedTtlSeconds.mockReturnValue(777);

      const result = await resendVerificationEmailAction({
        ctx: mockCtx,
        parsedInput: {
          ...validInput,
          callbackUrl: "http://localhost:3000/api/auth/sso/recovery/complete?state=test-state",
        },
      } as unknown as Parameters<typeof resendVerificationEmailAction>[0]);

      // The link and the intent have to get ONE lifetime, or the survivor of the two ends recovery on
      // its own: a longer-lived link signs the user in and then reports failure. `777` is not a TTL
      // either call site could arrive at by itself, so it fails if either computes its own instead of
      // taking the paired value. Deleting the refresh entirely also left the whole suite green once.
      expect(recoveryIntentMocks.getSsoRecoveryPairedTtlSeconds).toHaveBeenCalledWith({
        callbackUrl: "http://localhost:3000",
        email: mockVerifiedUser.email,
        provider: "google",
        providerAccountId: "provider_123",
        userId: mockVerifiedUser.id,
        createdAt: expect.any(Number),
      });
      expect(recoveryIntentMocks.refreshSsoRecoveryIntent).toHaveBeenCalledWith("test-state", 777);
      expect(sendVerificationEmail).toHaveBeenCalledWith({
        id: mockVerifiedUser.id,
        email: mockVerifiedUser.email,
        locale: "en-US",
        callbackUrl: "http://localhost:3000/api/auth/sso/recovery/complete?state=test-state",
        purpose: "sso_recovery",
        linkTtlSeconds: 777,
        // The resent link is bound to the same recovery as the first (ENG-7310).
        ssoRecoveryStateId: "test-state",
      });
      expect(result).toEqual({ success: true });
    });

    /**
     * Next resolves `…/complete/` and `/api//auth/…/complete` to the completion route, so a stricter
     * comparison here made the resend no-op while this action still answered `{ success: true }` and
     * the UI toasted success.
     */
    test.each([
      ["a trailing slash", "http://localhost:3000/api/auth/sso/recovery/complete/?state=test-state"],
      ["an interior repeat", "http://localhost:3000/api//auth/sso/recovery/complete?state=test-state"],
    ])("treats a recovery callback with %s as recovery", async (_label, callbackUrl) => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail).mockResolvedValue({
        ...mockVerifiedUser,
        emailVerified: true,
        locale: "en-US",
        identityProvider: "email",
        isActive: true,
      } as never);
      recoveryIntentMocks.readSsoRecoveryIntent.mockResolvedValue({
        callbackUrl: "http://localhost:3000",
        email: mockVerifiedUser.email,
        provider: "google",
        providerAccountId: "provider_123",
        userId: mockVerifiedUser.id,
        createdAt: Date.now(),
      });

      await resendVerificationEmailAction({
        ctx: mockCtx,
        parsedInput: { ...validInput, callbackUrl },
      } as unknown as Parameters<typeof resendVerificationEmailAction>[0]);

      expect(sendVerificationEmail).toHaveBeenCalledWith(
        expect.objectContaining({ purpose: "sso_recovery" })
      );
      expect(recoveryIntentMocks.refreshSsoRecoveryIntent).toHaveBeenCalled();
    });

    /**
     * The state id is recovery-shaped but nothing is stored under it. The server cannot tell an expired
     * intent from a consumed one or an invented one — `readSsoRecoveryIntent` returns `null` for all
     * three — so they get one answer, and it is the honest one for the case that actually happens.
     *
     * This test previously asserted `{ success: true }` here, which is what stranded a user whose link
     * had aged out: no mail was sent, and the page toasted that one had been.
     */
    test("reports an expired recovery link rather than a success with no mail sent", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      const verifiedUserWithLocale: NonNullable<Awaited<ReturnType<typeof getUserByEmail>>> = {
        ...mockVerifiedUser,
        emailVerified: true,
        locale: "en-US",
        identityProvider: "email",
        isActive: true,
      };
      vi.mocked(getUserByEmail).mockResolvedValue(verifiedUserWithLocale);

      // Thrown rather than returned: these tests drive the wrapped handler directly, so
      // `handleServerError` — which turns an expected error into the action's `serverError`, and is
      // what the form reads — is not in the path here. `InvalidInputError` is on the expected list, so
      // the code reaches the client rather than being masked as a generic server error.
      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: {
            ...validInput,
            callbackUrl: "http://localhost:3000/api/auth/sso/recovery/complete?state=forged-state",
          },
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow(SSO_RECOVERY_LINK_EXPIRED_ERROR_CODE);

      expect(sendVerificationEmail).not.toHaveBeenCalled();
    });

    test("should fall back to a normal verification email when the recovery intent belongs to a different email", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail, { partial: true }).mockResolvedValue(mockUser);
      recoveryIntentMocks.readSsoRecoveryIntent.mockResolvedValue({
        callbackUrl: "http://localhost:3000",
        email: "other@example.com",
        provider: "google",
        providerAccountId: "provider_123",
        userId: "user_123",
        createdAt: Date.now(),
      });

      const result = await resendVerificationEmailAction({
        ctx: mockCtx,
        parsedInput: {
          ...validInput,
          callbackUrl: "http://localhost:3000/api/auth/sso/recovery/complete?state=test-state",
        },
      } as unknown as Parameters<typeof resendVerificationEmailAction>[0]);

      expect(auth.api.sendVerificationEmail).toHaveBeenCalledWith({
        body: {
          email: mockUser.email,
          callbackURL: "http://localhost:3000/api/auth/sso/recovery/complete?state=test-state",
        },
        headers: expect.any(Headers),
      });
      expect(result).toEqual({ success: true });
    });

    // ENG-2562: a resent link gets a fresh hour while the intent cookie's clock started at sign-up, so
    // the action re-pairs the cookie with the new link — but only for a browser that already holds a
    // valid cookie naming this user. Anything weaker would let an unauthenticated caller arm sign-up
    // proof for an arbitrary account by asking for a resend.
    describe("Sign-up intent cookie refresh (ENG-2562)", () => {
      beforeEach(() => {
        vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
        vi.mocked(getUserByEmail).mockResolvedValue(mockUser as never);
        cookieMocks.get.mockReturnValue({ value: "existing-intent-cookie" });
      });

      test("re-issues the cookie when the browser already holds a valid one for this user", async () => {
        signupIntentMocks.classifySignupIntent.mockReturnValue("valid");

        await resendVerificationEmailAction({ ctx: mockCtx, parsedInput: validInput } as never);

        expect(signupIntentMocks.classifySignupIntent).toHaveBeenCalledWith(
          "existing-intent-cookie",
          mockUser.id
        );
        expect(signupIntentMocks.createSignupIntentToken).toHaveBeenCalledWith(mockUser.id);
        expect(cookieMocks.set).toHaveBeenCalledWith(
          "formbricks.signup_intent",
          "fresh-intent-token",
          expect.objectContaining({ httpOnly: true, maxAge: 3600 })
        );
      });

      test.each([["absent"], ["invalid"], ["other_user"]])(
        "does not mint a cookie when the browser's proof classifies as %s",
        async (classification) => {
          signupIntentMocks.classifySignupIntent.mockReturnValue(classification);

          await resendVerificationEmailAction({ ctx: mockCtx, parsedInput: validInput } as never);

          expect(signupIntentMocks.createSignupIntentToken).not.toHaveBeenCalled();
          expect(cookieMocks.set).not.toHaveBeenCalled();
        }
      );

      test("does not touch the cookie when the user is already verified (no email sent)", async () => {
        vi.mocked(getUserByEmail).mockResolvedValue(mockVerifiedUser as never);
        signupIntentMocks.classifySignupIntent.mockReturnValue("valid");

        await resendVerificationEmailAction({ ctx: mockCtx, parsedInput: validInput } as never);

        expect(cookieMocks.set).not.toHaveBeenCalled();
      });
    });

    test("should throw ResourceNotFoundError when user doesn't exist", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail).mockResolvedValue(null);

      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: validInput,
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow(ResourceNotFoundError);

      expect(applyIPRateLimit).toHaveBeenCalled();
      expect(getUserByEmail).toHaveBeenCalledWith(validInput.email);
      expect(sendVerificationEmail).not.toHaveBeenCalled();
    });
  });

  describe("Audit Logging", () => {
    test("should set audit context userId when sending verification email", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail, { partial: true }).mockResolvedValue(mockUser);

      const testCtx = {
        auditLoggingCtx: {
          organizationId: "",
          userId: "",
        },
      };

      await resendVerificationEmailAction({
        ctx: testCtx,
        parsedInput: validInput,
      } as unknown as Parameters<typeof resendVerificationEmailAction>[0]);

      // The userId should be set in the audit context
      expect(testCtx.auditLoggingCtx.userId).toBe(mockUser.id);
    });

    test("should not set audit context userId when email is already verified", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail, { partial: true }).mockResolvedValue(mockVerifiedUser);

      const testCtx = {
        auditLoggingCtx: {
          organizationId: "",
          userId: "",
        },
      };

      await resendVerificationEmailAction({
        ctx: testCtx,
        parsedInput: validInput,
      } as unknown as Parameters<typeof resendVerificationEmailAction>[0]);

      // The userId should not be set since no email was sent
      expect(testCtx.auditLoggingCtx.userId).toBe("");
    });
  });

  describe("Error Handling", () => {
    test("should propagate rate limiting errors", async () => {
      const rateLimitError = new Error("Maximum number of requests reached. Please try again later.");
      vi.mocked(applyIPRateLimit).mockRejectedValue(rateLimitError);

      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: validInput,
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow("Maximum number of requests reached. Please try again later.");
    });

    test("should handle user lookup errors after rate limiting", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail).mockRejectedValue(new Error("Database error"));

      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: validInput,
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow("Database error");

      expect(applyIPRateLimit).toHaveBeenCalled();
    });

    test("should handle email sending errors after rate limiting", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail, { partial: true }).mockResolvedValue(mockUser);
      vi.mocked(auth.api.sendVerificationEmail).mockRejectedValue(new Error("Email service error"));

      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: validInput,
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow("Email service error");

      expect(applyIPRateLimit).toHaveBeenCalled();
      expect(getUserByEmail).toHaveBeenCalled();
    });
  });

  describe("Input Validation", () => {
    test("should handle empty email input", async () => {
      const invalidInput = { email: "" };

      // This would be caught by the Zod schema validation in the actual action
      // but we test the behavior if it somehow gets through
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail).mockResolvedValue(null);

      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: invalidInput,
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow(ResourceNotFoundError);
    });

    test("should handle malformed email input", async () => {
      const invalidInput = { email: "invalid-email" };

      // This would be caught by the Zod schema validation in the actual action
      // but we test the behavior if it somehow gets through
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail).mockResolvedValue(null);

      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: invalidInput,
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow(ResourceNotFoundError);
    });
  });

  describe("Security Considerations", () => {
    test("should always apply rate limiting regardless of user existence", async () => {
      vi.mocked(getUserByEmail).mockResolvedValue(null);

      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: validInput,
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow(ResourceNotFoundError);

      expect(applyIPRateLimit).toHaveBeenCalled();
    });

    test("should not leak information about user existence through different error messages", async () => {
      vi.mocked(applyIPRateLimit).mockResolvedValue({ allowed: true });
      vi.mocked(getUserByEmail).mockResolvedValue(null);

      // Both non-existent users should throw the same ResourceNotFoundError
      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: validInput,
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow(ResourceNotFoundError);

      const anotherEmail = { email: "another@example.com" };
      await expect(
        resendVerificationEmailAction({
          ctx: mockCtx,
          parsedInput: anotherEmail,
        } as unknown as Parameters<typeof resendVerificationEmailAction>[0])
      ).rejects.toThrow(ResourceNotFoundError);
    });
  });
});
