import { beforeEach, describe, expect, test, vi } from "vitest";
import type { JobExecutionContext } from "@formbricks/jobs";
import {
  activateEmailAuditErasureIntent,
  processEmailAuditMaintenanceJob,
  requestEmailAuditErasure,
  requestEmailAuditErasureBeforeUserDeletion,
  requestEmailAuditErasureRequired,
} from "./email-audit-maintenance";

vi.mock("crypto", async () => await vi.importActual<typeof import("crypto")>("crypto"));

const jobContext: JobExecutionContext = {
  attempt: 1,
  jobId: "email-audit-maintenance-test",
  jobName: "email-audit.maintain",
  maxAttempts: 3,
  queueName: "background-jobs",
};

const mocks = vi.hoisted(() => ({
  findMany: vi.fn(),
  findFirst: vi.fn(),
  updateMany: vi.fn(),
  update: vi.fn(),
  deleteMany: vi.fn(),
  deleteSnapshot: vi.fn(),
  getMac: vi.fn(),
  reportFailure: vi.fn(),
  warn: vi.fn(),
  queryRaw: vi.fn(),
  executeRaw: vi.fn(),
  intentCreate: vi.fn(),
  intentUpdateMany: vi.fn(),
  intentDeleteMany: vi.fn(),
  userFindMany: vi.fn(),
  bucket: "private-audit-bucket" as string | undefined,
}));

vi.mock("@formbricks/database", () => {
  const transactionClient = {
    outboundEmailAudit: {
      findMany: mocks.findMany,
      findFirst: mocks.findFirst,
      updateMany: mocks.updateMany,
      update: mocks.update,
      deleteMany: mocks.deleteMany,
    },
    outboundEmailAuditErasureIntent: {
      create: mocks.intentCreate,
      updateMany: mocks.intentUpdateMany,
      deleteMany: mocks.intentDeleteMany,
    },
    user: { findMany: mocks.userFindMany },
    $queryRaw: mocks.queryRaw,
    $executeRaw: mocks.executeRaw,
  };
  return {
    prisma: {
      ...transactionClient,
      $transaction: vi.fn(async (callback) => callback(transactionClient)),
    },
  };
});
vi.mock("@formbricks/logger", () => ({ logger: { warn: mocks.warn } }));
vi.mock("@/lib/constants", () => ({
  get EMAIL_SEND_AUDIT_BUCKET() {
    return mocks.bucket;
  },
  EMAIL_SEND_AUDIT_HMAC_KEY_ARN: "hmac-key",
}));
vi.mock("./email-audit-storage", () => ({
  deleteEmailAuditSnapshot: mocks.deleteSnapshot,
  getEmailAuditRecipientMac: mocks.getMac,
}));
vi.mock("./email-audit-monitoring", () => ({ reportEmailAuditFailure: mocks.reportFailure }));

describe("email audit retention and erasure", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mocks.bucket = "private-audit-bucket";
    mocks.findMany.mockResolvedValue([]);
    mocks.findFirst.mockResolvedValue(null);
    mocks.updateMany.mockResolvedValue({ count: 0 });
    mocks.update.mockResolvedValue({});
    mocks.deleteMany.mockResolvedValue({ count: 0 });
    mocks.deleteSnapshot.mockResolvedValue(undefined);
    mocks.getMac.mockResolvedValue("recipient-mac");
    mocks.reportFailure.mockResolvedValue(undefined);
    mocks.queryRaw.mockResolvedValue([]);
    mocks.executeRaw.mockResolvedValue(0);
    mocks.intentCreate.mockResolvedValue({});
    mocks.intentUpdateMany.mockResolvedValue({ count: 0 });
    mocks.intentDeleteMany.mockResolvedValue({ count: 0 });
    mocks.userFindMany.mockResolvedValue([]);
  });

  test("requests erasure by normalized recipient identity without storing an address", async () => {
    await requestEmailAuditErasure({ email: "Person@Example.com" });
    expect(mocks.getMac).toHaveBeenCalledWith("Person@Example.com", "hmac-key");
    expect(mocks.updateMany).toHaveBeenCalledWith({
      where: { OR: [{ recipientMac: "recipient-mac" }], erasedAt: null },
      data: { erasureRequestedAt: expect.any(Date), contentDeleteRetryAt: null },
    });
    expect(JSON.stringify(mocks.updateMany.mock.calls)).not.toContain("Person@Example.com");
  });

  test("does not silently skip email-only erasure when the HMAC service fails", async () => {
    mocks.getMac.mockRejectedValueOnce(new Error("kms unavailable"));

    await expect(requestEmailAuditErasure({ email: "Person@Example.com" })).rejects.toThrow("recipient_hmac");
    expect(mocks.updateMany).not.toHaveBeenCalled();
  });

  test("stops before marking rows if recipient matching fails during user deletion", async () => {
    mocks.getMac.mockRejectedValueOnce(new Error("kms unavailable"));

    await expect(requestEmailAuditErasure({ userId: "user-1", email: "Person@Example.com" })).rejects.toThrow(
      "recipient_hmac"
    );

    expect(mocks.updateMany).not.toHaveBeenCalled();
  });

  test("rejects an identifier-based erasure failure so source deletion can roll back", async () => {
    mocks.updateMany.mockRejectedValueOnce(new Error("database unavailable"));

    await expect(
      requestEmailAuditErasureRequired({ organizationId: "org-1" }, {
        outboundEmailAudit: { updateMany: mocks.updateMany },
      } as never)
    ).rejects.toThrow("database unavailable");

    expect(mocks.reportFailure).toHaveBeenCalledWith("email_audit_erasure_request_failed", {
      phase: undefined,
    });
  });

  test("rejects missing bucket configuration while audit rows remain, even with sending disabled", async () => {
    mocks.bucket = undefined;
    mocks.findFirst.mockResolvedValueOnce({ id: "audit-1" });

    await expect(requestEmailAuditErasure({ organizationId: "org-1" })).rejects.toThrow(
      "Email audit bucket configuration is missing while audit rows remain"
    );
    expect(mocks.updateMany).not.toHaveBeenCalled();
  });

  test("permits deployments without an audit store when no audit rows exist", async () => {
    mocks.bucket = undefined;

    await expect(requestEmailAuditErasure({ organizationId: "org-1" })).resolves.toBeUndefined();
    expect(mocks.findFirst).toHaveBeenCalledWith({ select: { id: true } });
  });

  test("signals missing storage configuration when retained audit rows exist", async () => {
    mocks.bucket = undefined;
    mocks.findFirst.mockResolvedValueOnce({ id: "audit-1" });

    await expect(processEmailAuditMaintenanceJob({ scope: "global" }, jobContext)).rejects.toThrow(
      "Email audit bucket configuration is missing while audit rows remain"
    );
    expect(mocks.reportFailure).toHaveBeenCalledWith("email_audit_gap", { phase: "bucket_config" });
  });

  test("blocks user deletion while recipient erasure cannot be queued", async () => {
    mocks.getMac.mockRejectedValueOnce(new Error("kms unavailable"));

    await expect(requestEmailAuditErasureBeforeUserDeletion("user-1", "Person@Example.com")).rejects.toThrow(
      "Email audit erasure could not be prepared"
    );
    expect(mocks.reportFailure).toHaveBeenCalledWith("email_audit_erasure_request_failed", {
      phase: "recipient_hmac",
    });
  });

  test("persists a recipient intent with the account erasure mark", async () => {
    await requestEmailAuditErasureBeforeUserDeletion("user-1", "Person@Example.com");

    expect(mocks.intentCreate).toHaveBeenCalledWith({
      data: {
        userId: "user-1",
        userHash: expect.stringMatching(/^[a-f0-9]{64}$/),
        recipientMac: "recipient-mac",
        expiresAt: expect.any(Date),
      },
    });
    expect(mocks.updateMany).toHaveBeenCalledWith({
      where: { recipientMac: "recipient-mac", erasedAt: null },
      data: { erasureRequestedAt: expect.any(Date), contentDeleteRetryAt: null },
    });
  });

  test("removes the raw user id once deletion is confirmed", async () => {
    await activateEmailAuditErasureIntent("user-1");
    expect(mocks.intentUpdateMany).toHaveBeenCalledWith({
      where: { userId: "user-1", activatedAt: null },
      data: { userId: null, activatedAt: expect.any(Date) },
    });
  });

  test("activates an intent after interrupted account deletion and marks late audit rows", async () => {
    mocks.queryRaw.mockResolvedValueOnce([{ id: "intent-1", userId: "deleted-user" }]);
    mocks.executeRaw.mockResolvedValueOnce(1);

    await processEmailAuditMaintenanceJob({ scope: "global" }, jobContext);

    expect(mocks.intentUpdateMany).toHaveBeenCalledWith({
      where: { id: { in: ["intent-1"] } },
      data: { userId: null, activatedAt: expect.any(Date), checkedAt: expect.any(Date) },
    });
    const lateRowQuery = (mocks.executeRaw.mock.calls[0][0] as TemplateStringsArray).join(" ");
    expect(lateRowQuery).toContain('i."userHash" = a."actorUserHash"');
    expect(lateRowQuery).toContain('i."userHash" = a."configuredByUserHash"');
    expect(lateRowQuery).toContain('i."recipientMac" = a."recipientMac"');
    expect(lateRowQuery).toContain('a."createdAt" <= i."activatedAt"');
  });

  test("requests erasure for bulk-deleted responses in bounded batches", async () => {
    const responseIds = Array.from({ length: 501 }, (_, index) => `response-${index}`);

    await requestEmailAuditErasure({ responseIds });

    expect(mocks.updateMany).toHaveBeenCalledTimes(2);
    expect(mocks.updateMany).toHaveBeenNthCalledWith(1, {
      where: { responseId: { in: responseIds.slice(0, 500) }, erasedAt: null },
      data: { erasureRequestedAt: expect.any(Date), contentDeleteRetryAt: null },
    });
    expect(mocks.updateMany).toHaveBeenNthCalledWith(2, {
      where: { responseId: { in: responseIds.slice(500) }, erasedAt: null },
      data: { erasureRequestedAt: expect.any(Date), contentDeleteRetryAt: null },
    });
  });

  test("marks interrupted attempts indeterminate and removes erased content and identifiers", async () => {
    const before = Date.now();
    mocks.findMany
      .mockResolvedValueOnce([{ id: "stale-id" }])
      .mockResolvedValueOnce([
        {
          id: "erased-id",
          snapshotKey: "email-audit/erased-id.json",
          erasureRequestedAt: new Date(),
          contentDeleteFailures: 0,
        },
      ])
      .mockResolvedValueOnce([{ id: "expired-id" }]);

    await processEmailAuditMaintenanceJob({ scope: "global" }, jobContext);

    const erasureCutoff = mocks.findMany.mock.calls[1][0].where.AND[0].OR[0].erasureRequestedAt.lte as Date;
    expect(erasureCutoff.getTime()).toBeGreaterThanOrEqual(before - 60_000);
    expect(erasureCutoff.getTime()).toBeLessThanOrEqual(Date.now() - 60_000);

    expect(mocks.updateMany).toHaveBeenCalledWith({
      where: { id: { in: ["stale-id"] }, status: "prepared" },
      data: { status: "indeterminate", statusRecordedAt: expect.any(Date), auditGap: true },
    });
    expect(mocks.deleteSnapshot).toHaveBeenCalledWith("private-audit-bucket", "erased-id");
    expect(mocks.updateMany).toHaveBeenCalledWith({
      where: {
        id: "erased-id",
        snapshotKey: "email-audit/erased-id.json",
        erasureRequestedAt: { not: null },
        erasedAt: null,
      },
      data: expect.objectContaining({
        snapshotKey: null,
        recipientMac: null,
        organizationId: null,
        actorUserId: null,
        actorUserHash: null,
        configuredByUserHash: null,
        status: "erased",
        erasedAt: expect.any(Date),
      }),
    });
    expect(mocks.deleteMany).toHaveBeenCalledWith({ where: { id: { in: ["expired-id"] } } });
    expect(mocks.reportFailure).toHaveBeenCalledWith("email_audit_stale_prepared", { count: 1 });
  });

  test("keeps an erasure request pending when S3 deletion fails", async () => {
    const before = Date.now();
    mocks.findMany
      .mockResolvedValueOnce([])
      .mockResolvedValueOnce([
        {
          id: "erased-id",
          snapshotKey: "email-audit/erased-id.json",
          erasureRequestedAt: new Date(),
          contentDeleteFailures: 0,
        },
      ])
      .mockResolvedValueOnce([]);
    mocks.deleteSnapshot.mockRejectedValueOnce(new Error("S3 unavailable"));

    await processEmailAuditMaintenanceJob({ scope: "global" }, jobContext);

    expect(mocks.updateMany).toHaveBeenCalledWith({
      where: { id: "erased-id", erasedAt: null },
      data: {
        contentDeleteFailures: { increment: 1 },
        contentDeleteRetryAt: expect.any(Date),
      },
    });
    const retryAt = mocks.updateMany.mock.calls[0][0].data.contentDeleteRetryAt as Date;
    expect(retryAt.getTime()).toBeGreaterThanOrEqual(before + 15 * 60_000);
    expect(retryAt.getTime()).toBeLessThanOrEqual(Date.now() + 15 * 60_000);
    expect(mocks.reportFailure).toHaveBeenCalledWith("email_audit_content_delete_failed", {
      auditId: "erased-id",
    });
  });
});
