import { createHmac, randomUUID } from "node:crypto";
import assert from "node:assert/strict";
import test from "node:test";
import { buildApp } from "../../../app.js";
import { env } from "../../../env.js";
import { verifyKommoWidgetRequestToken } from "../../../lib/kommo.js";
import { prisma } from "../../../lib/prisma.js";

type Fixture = {
  lawFirmId: string;
  lawFirmSlug: string;
  officeId: string;
  userId: string;
  userEmail: string;
};

async function createFixture() {
  const suffix = randomUUID().slice(0, 8);
  const fixture: Fixture = {
    lawFirmId: randomUUID(),
    lawFirmSlug: `kommo-${suffix}`,
    officeId: randomUUID(),
    userId: randomUUID(),
    userEmail: `kommo-${suffix}@example.com`,
  };

  await prisma.$executeRaw`
    INSERT INTO law_firms (
      id, name, legal_name, slug, timezone, default_locale, status, created_at, updated_at
    ) VALUES (
      ${fixture.lawFirmId},
      ${`Kommo Test ${suffix}`},
      ${`Kommo Test ${suffix}`},
      ${fixture.lawFirmSlug},
      'America/New_York',
      'pt-BR',
      'active',
      CURRENT_TIMESTAMP,
      CURRENT_TIMESTAMP
    )
  `;

  await prisma.$executeRaw`
    INSERT INTO offices (
      id, law_firm_id, name, code, timezone, is_headquarters, created_at, updated_at
    ) VALUES (
      ${fixture.officeId},
      ${fixture.lawFirmId},
      'Main office',
      ${`KM${suffix}`},
      'America/New_York',
      1,
      CURRENT_TIMESTAMP,
      CURRENT_TIMESTAMP
    )
  `;

  await prisma.$executeRaw`
    INSERT INTO users (
      id, law_firm_id, primary_office_id, first_name, last_name, display_name, email,
      auth_provider, locale, timezone, is_active, created_at, updated_at
    ) VALUES (
      ${fixture.userId},
      ${fixture.lawFirmId},
      ${fixture.officeId},
      'Ana',
      'Kommo',
      'Ana Kommo',
      ${fixture.userEmail},
      'local',
      'pt-BR',
      'America/New_York',
      1,
      CURRENT_TIMESTAMP,
      CURRENT_TIMESTAMP
    )
  `;

  await prisma.$executeRaw`
    INSERT INTO workspace_memberships (
      id, law_firm_id, user_id, membership_role, is_default, created_by_user_id, joined_at
    ) VALUES (
      ${randomUUID()},
      ${fixture.lawFirmId},
      ${fixture.userId},
      'admin',
      1,
      ${fixture.userId},
      CURRENT_TIMESTAMP
    )
  `;

  return fixture;
}

async function cleanupFixture(fixture: Fixture) {
  await prisma.$executeRaw`DELETE FROM audit_logs WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM law_firm_kommo_settings WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM kommo_outbound_deliveries WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM kommo_lead_messages WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM kommo_leads WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM messages WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM conversations WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM repository_items WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM workspace_memberships WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM cases WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM clients WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM users WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM offices WHERE law_firm_id = ${fixture.lawFirmId}`;
  await prisma.$executeRaw`DELETE FROM law_firms WHERE id = ${fixture.lawFirmId}`;
}

async function createClientRecord(input: {
  fixture: Fixture;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
}) {
  const clientId = randomUUID();

  await prisma.$executeRaw`
    INSERT INTO clients (
      id,
      law_firm_id,
      primary_office_id,
      client_number,
      first_name,
      last_name,
      email,
      phone,
      preferred_language,
      created_by_user_id,
      created_at,
      updated_at
    ) VALUES (
      ${clientId},
      ${input.fixture.lawFirmId},
      ${input.fixture.officeId},
      ${`CL-${randomUUID().slice(0, 6)}`},
      ${input.firstName},
      ${input.lastName},
      ${input.email},
      ${input.phone},
      'pt-BR',
      ${input.fixture.userId},
      CURRENT_TIMESTAMP,
      CURRENT_TIMESTAMP
    )
  `;

  return clientId;
}

function toBase64Url(value: string) {
  return Buffer.from(value, "utf8")
    .toString("base64")
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/g, "");
}

function createHs256Jwt(payload: Record<string, unknown>, secret: string) {
  const header = {
    alg: "HS256",
    typ: "JWT",
  };
  const encodedHeader = toBase64Url(JSON.stringify(header));
  const encodedPayload = toBase64Url(JSON.stringify(payload));
  const signature = createHmac("sha256", secret)
    .update(`${encodedHeader}.${encodedPayload}`)
    .digest("base64")
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/g, "");

  return `${encodedHeader}.${encodedPayload}.${signature}`;
}

test("Kommo Salesbot JWT tokens can be verified with the integration secret key", () => {
  const now = new Date("2026-03-30T12:00:00.000Z");
  const token = createHs256Jwt(
    {
      iss: "https://sample.kommo.com",
      subdomain: "sample",
      account_id: 123,
      user_id: 456,
      client_uuid: "client-uuid",
      iat: Math.floor(now.getTime() / 1000) - 60,
      nbf: Math.floor(now.getTime() / 1000) - 60,
      exp: Math.floor(now.getTime() / 1000) + 300,
    },
    "integration-secret",
  );

  const payload = verifyKommoWidgetRequestToken({
    token,
    secretKey: "integration-secret",
    now,
  });

  assert.equal(payload.account_id, 123);
  assert.equal(payload.user_id, 456);
  assert.equal(payload.subdomain, "sample");
});

test("Kommo credentials can be saved per workspace and are reflected in the integration summary", async () => {
  const fixture = await createFixture();
  const app = buildApp();

  try {
    await app.ready();

    const token = app.jwt.sign({
      userId: fixture.userId,
      lawFirmId: fixture.lawFirmId,
      lawFirmSlug: fixture.lawFirmSlug,
      email: fixture.userEmail,
      roleCodes: ["admin"],
      displayName: "Ana Kommo",
    });

    const saveResponse = await app.inject({
      method: "POST",
      url: "/integrations/kommo/settings",
      headers: {
        cookie: `${env.COOKIE_NAME}=${encodeURIComponent(token)}`,
      },
      payload: {
        subdomain: "workspace-demo",
        accessToken: "kommo-access-token-1234567890",
        webhookSecret: "workspace-webhook-secret",
        integrationSecretKey: "workspace-salesbot-secret",
      },
    });

    assert.equal(saveResponse.statusCode, 201);

    const summaryResponse = await app.inject({
      method: "GET",
      url: "/integrations/kommo/summary",
      headers: {
        cookie: `${env.COOKIE_NAME}=${encodeURIComponent(token)}`,
      },
    });

    assert.equal(summaryResponse.statusCode, 200);

    const summary = summaryResponse.json() as {
      subdomain: string | null;
      apiConfigured: boolean;
      accessTokenConfigured: boolean;
      accessTokenLast4: string | null;
      webhookSecretConfigured: boolean;
      salesbotSecretConfigured: boolean;
      salesbotSecretKeyLast4: string | null;
      webhookSecret: string | null;
    };

    assert.equal(summary.subdomain, "workspace-demo");
    assert.equal(summary.apiConfigured, true);
    assert.equal(summary.accessTokenConfigured, true);
    assert.equal(summary.accessTokenLast4, "7890");
    assert.equal(summary.webhookSecretConfigured, true);
    assert.equal(summary.salesbotSecretConfigured, true);
    assert.equal(summary.salesbotSecretKeyLast4, "cret");
    assert.equal(summary.webhookSecret, "workspace-webhook-secret");
  } finally {
    await app.close();
    await cleanupFixture(fixture);
  }
});

test("Kommo lead webhook stores an unlinked local lead only once", async () => {
  const fixture = await createFixture();
  const app = buildApp();

  try {
    await app.ready();

    const body = new URLSearchParams({
      "leads[add][0][id]": "9001",
      "leads[add][0][name]": "Maria Silva",
      "leads[add][0][custom_fields][0][code]": "PHONE",
      "leads[add][0][custom_fields][0][values][0][value]": "+1 555 123 4567",
      "leads[add][0][custom_fields][1][code]": "EMAIL",
      "leads[add][0][custom_fields][1][values][0][value]": "maria@example.com",
    }).toString();

    const firstResponse = await app.inject({
      method: "POST",
      url: `/webhook/kommo?workspaceKey=${encodeURIComponent(fixture.lawFirmSlug)}`,
      headers: {
        "content-type": "application/x-www-form-urlencoded",
      },
      payload: body,
    });

    assert.equal(firstResponse.statusCode, 200);

    const secondResponse = await app.inject({
      method: "POST",
      url: `/webhook/kommo?workspaceKey=${encodeURIComponent(fixture.lawFirmSlug)}`,
      headers: {
        "content-type": "application/x-www-form-urlencoded",
      },
      payload: body,
    });

    assert.equal(secondResponse.statusCode, 200);

    const [clients, cases, leadRows] = await Promise.all([
      prisma.client.findMany({
        where: {
          law_firm_id: fixture.lawFirmId,
          deleted_at: null,
        },
      }),
      prisma.caseRecord.findMany({
        where: {
          law_firm_id: fixture.lawFirmId,
          deleted_at: null,
        },
      }),
      prisma.$queryRaw<
        Array<{
          kommo_lead_id: string;
          display_name: string;
          email: string | null;
          phone: string | null;
          linked_client_id: string | null;
          status_code: string;
        }>
      >`
        SELECT kommo_lead_id, display_name, email, phone, linked_client_id, status_code
        FROM kommo_leads
        WHERE law_firm_id = ${fixture.lawFirmId}
          AND kommo_lead_id = ${"9001"}
      `,
    ]);

    assert.equal(clients.length, 0);
    assert.equal(cases.length, 0);
    assert.equal(leadRows.length, 1);
    assert.equal(leadRows[0]?.kommo_lead_id, "9001");
    assert.equal(leadRows[0]?.display_name, "Maria Silva");
    assert.equal(leadRows[0]?.email, "maria@example.com");
    assert.equal(leadRows[0]?.phone, "+15551234567");
    assert.equal(leadRows[0]?.linked_client_id, null);
    assert.equal(leadRows[0]?.status_code, "unlinked");
  } finally {
    await app.close();
    await cleanupFixture(fixture);
  }
});

test("Kommo Salesbot inbound lead can be linked manually before replying through repository messages", async () => {
  const fixture = await createFixture();
  const app = buildApp();
  const originalFetch = globalThis.fetch;
  const fetchCalls: Array<{ url: string; body: string }> = [];

  globalThis.fetch = async (input, init) => {
    fetchCalls.push({
      url: String(input),
      body: typeof init?.body === "string" ? init.body : "",
    });

    return new Response(JSON.stringify({ ok: true }), {
      status: 200,
      headers: {
        "content-type": "application/json",
      },
    });
  };

  try {
    await app.ready();

    const token = app.jwt.sign({
      userId: fixture.userId,
      lawFirmId: fixture.lawFirmId,
      lawFirmSlug: fixture.lawFirmSlug,
      email: fixture.userEmail,
      roleCodes: ["admin"],
      displayName: "Ana Kommo",
    });

    const inboundResponse = await app.inject({
      method: "POST",
      url: `/webhook/kommo/salesbot/messages?workspaceKey=${encodeURIComponent(fixture.lawFirmSlug)}`,
      payload: {
        data: {
          lead: "lead-77",
          message: "Oi, quero ajuda com meu caso.",
          senderName: "Carlos",
          chatId: "chat-55",
        },
        return_url: "https://kommo.example/return/123",
        token: "salesbot-token-1",
      },
    });

    assert.equal(inboundResponse.statusCode, 200);

    const inboundPayload = inboundResponse.json() as {
      leadRecordId: string;
      conversationId: string | null;
      clientId: string | null;
      caseId: string | null;
      isLinked: boolean;
    };

    assert.equal(inboundPayload.clientId, null);
    assert.equal(inboundPayload.conversationId, null);
    assert.equal(inboundPayload.isLinked, false);

    const unlinkedResponse = await app.inject({
      method: "GET",
      url: "/integrations/kommo/leads?status=unlinked",
      headers: {
        cookie: `${env.COOKIE_NAME}=${encodeURIComponent(token)}`,
      },
    });

    assert.equal(unlinkedResponse.statusCode, 200);

    const unlinkedPayload = unlinkedResponse.json() as Array<{
      id: string;
      leadId: string;
      unreadMessageCount: number;
      lastMessagePreview: string | null;
    }>;

    assert.equal(unlinkedPayload.length, 1);
    assert.equal(unlinkedPayload[0]?.id, inboundPayload.leadRecordId);
    assert.equal(unlinkedPayload[0]?.leadId, "lead-77");
    assert.equal(unlinkedPayload[0]?.unreadMessageCount, 1);
    assert.equal(unlinkedPayload[0]?.lastMessagePreview, "Oi, quero ajuda com meu caso.");

    const clientId = await createClientRecord({
      fixture,
      firstName: "Carlos",
      lastName: "Souza",
      email: "carlos@example.com",
      phone: "+15557654321",
    });

    const linkResponse = await app.inject({
      method: "POST",
      url: `/integrations/kommo/leads/${inboundPayload.leadRecordId}/link-client`,
      headers: {
        cookie: `${env.COOKIE_NAME}=${encodeURIComponent(token)}`,
      },
      payload: {
        clientId,
      },
    });

    assert.equal(linkResponse.statusCode, 200);

    const linkedPayload = linkResponse.json() as {
      clientId: string | null;
      conversationId: string | null;
    };

    assert.equal(linkedPayload.clientId, clientId);
    assert.ok(linkedPayload.conversationId, "expected conversation id after linking Kommo lead");

    const inboundRepositoryMessages = await prisma.$queryRaw<
      Array<{
        message_direction: string;
      }>
    >`
      SELECT message_direction
      FROM messages
      WHERE law_firm_id = ${fixture.lawFirmId}
      ORDER BY created_at ASC
    `;

    assert.equal(inboundRepositoryMessages.length, 1);
    assert.equal(inboundRepositoryMessages[0]?.message_direction, "inbound");

    const outboundResponse = await app.inject({
      method: "POST",
      url: "/repository/messages",
      headers: {
        cookie: `${env.COOKIE_NAME}=${encodeURIComponent(token)}`,
      },
      payload: {
        clientId,
        caseId: null,
        channelCode: "whatsapp",
        bodyText: "Claro. Posso te orientar sobre os próximos passos.",
        directionCode: "outbound",
        conversationId: linkedPayload.conversationId,
      },
    });

    assert.equal(outboundResponse.statusCode, 201);
    assert.equal(fetchCalls.length, 1);
    assert.equal(fetchCalls[0]?.url, "https://kommo.example/return/123");

    const outboundBody = JSON.parse(fetchCalls[0]?.body ?? "{}") as {
      data?: { message?: string };
      execute_handlers?: Array<{ handler: string; params: { type: string; value: string } }>;
    };

    assert.equal(outboundBody.data?.message, "Claro. Posso te orientar sobre os próximos passos.");
    assert.equal(outboundBody.execute_handlers?.[0]?.handler, "show");
    assert.equal(outboundBody.execute_handlers?.[0]?.params.type, "text");

    const storedMessages = await prisma.$queryRaw<
      Array<{
        message_direction: string;
        message_status: string | null;
      }>
    >`
      SELECT message_direction, message_status
      FROM messages
      WHERE law_firm_id = ${fixture.lawFirmId}
      ORDER BY created_at ASC
    `;

    assert.equal(storedMessages.length, 2);
    assert.deepEqual(
      storedMessages.map((message) => message.message_direction).sort(),
      ["inbound", "outbound"],
    );
    assert.ok(
      storedMessages.some((message) => message.message_status === "sent_via_kommo_salesbot"),
      "expected one outbound Kommo reply stored with Salesbot status",
    );

    const kommoLeadMessages = await prisma.$queryRaw<
      Array<{
        direction_code: string;
      }>
    >`
      SELECT direction_code
      FROM kommo_lead_messages
      WHERE law_firm_id = ${fixture.lawFirmId}
      ORDER BY occurred_at ASC, created_at ASC
    `;

    assert.deepEqual(
      kommoLeadMessages.map((message) => message.direction_code).sort(),
      ["inbound", "outbound"],
    );
  } finally {
    globalThis.fetch = originalFetch;
    await app.close();
    await cleanupFixture(fixture);
  }
});

test("Kommo outbound delivery schedules retry, audits the failure, and recovers on dashboard bootstrap", async () => {
  const fixture = await createFixture();
  const app = buildApp();
  const originalFetch = globalThis.fetch;
  let failWith503 = true;
  let fetchCalls = 0;

  globalThis.fetch = async () => {
    fetchCalls += 1;

    if (failWith503) {
      return new Response("temporary outage", {
        status: 503,
        headers: {
          "content-type": "text/plain",
        },
      });
    }

    return new Response(JSON.stringify({ ok: true }), {
      status: 200,
      headers: {
        "content-type": "application/json",
      },
    });
  };

  try {
    await app.ready();

    const token = app.jwt.sign({
      userId: fixture.userId,
      lawFirmId: fixture.lawFirmId,
      lawFirmSlug: fixture.lawFirmSlug,
      email: fixture.userEmail,
      roleCodes: ["admin"],
      displayName: "Ana Kommo",
    });

    const inboundResponse = await app.inject({
      method: "POST",
      url: `/webhook/kommo/salesbot/messages?workspaceKey=${encodeURIComponent(fixture.lawFirmSlug)}`,
      payload: {
        data: {
          lead: "lead-retry-1",
          message: "Preciso de retorno urgente.",
          senderName: "Julia",
          chatId: "chat-retry-1",
        },
        return_url: "https://kommo.example/return/retry-1",
        token: "salesbot-token-retry-1",
      },
    });

    assert.equal(inboundResponse.statusCode, 200);

    const inboundPayload = inboundResponse.json() as {
      leadRecordId: string;
    };

    const clientId = await createClientRecord({
      fixture,
      firstName: "Julia",
      lastName: "Mendes",
      email: "julia@example.com",
      phone: "+15551230000",
    });

    const linkResponse = await app.inject({
      method: "POST",
      url: `/integrations/kommo/leads/${inboundPayload.leadRecordId}/link-client`,
      headers: {
        cookie: `${env.COOKIE_NAME}=${encodeURIComponent(token)}`,
      },
      payload: {
        clientId,
      },
    });

    assert.equal(linkResponse.statusCode, 200);

    const linkedPayload = linkResponse.json() as {
      conversationId: string | null;
    };

    assert.ok(linkedPayload.conversationId, "expected linked Kommo conversation");

    const outboundResponse = await app.inject({
      method: "POST",
      url: "/repository/messages",
      headers: {
        cookie: `${env.COOKIE_NAME}=${encodeURIComponent(token)}`,
      },
      payload: {
        clientId,
        caseId: null,
        channelCode: "whatsapp",
        bodyText: "Recebi sua mensagem e vou retornar em seguida.",
        directionCode: "outbound",
        conversationId: linkedPayload.conversationId,
      },
    });

    assert.equal(outboundResponse.statusCode, 201);
    assert.equal(fetchCalls, 2);

    const outboundPayload = outboundResponse.json() as {
      repositoryItemId: string;
      messageStatus: string;
      kommoDelivery: {
        deliveryId: string | null;
        nextRetryAt: string | null;
        lastErrorMessage: string | null;
      } | null;
    };

    assert.equal(outboundPayload.messageStatus, "kommo_retry_scheduled");
    assert.ok(outboundPayload.kommoDelivery?.deliveryId);
    assert.ok(outboundPayload.kommoDelivery?.nextRetryAt);
    assert.match(String(outboundPayload.kommoDelivery?.lastErrorMessage ?? ""), /503/);

    const scheduledMessages = await prisma.$queryRaw<
      Array<{
        message_status: string | null;
      }>
    >`
      SELECT message_status
      FROM messages
      WHERE law_firm_id = ${fixture.lawFirmId}
        AND repository_item_id = ${outboundPayload.repositoryItemId}
    `;

    assert.equal(scheduledMessages[0]?.message_status, "kommo_retry_scheduled");

    const scheduledDeliveries = await prisma.$queryRaw<
      Array<{
        status_code: string;
        attempt_count: number;
        repository_item_id: string | null;
        last_error_code: string | null;
      }>
    >`
      SELECT status_code, attempt_count, repository_item_id, last_error_code
      FROM kommo_outbound_deliveries
      WHERE law_firm_id = ${fixture.lawFirmId}
        AND id = ${outboundPayload.kommoDelivery?.deliveryId ?? ""}
    `;

    assert.equal(scheduledDeliveries[0]?.status_code, "retry_scheduled");
    assert.equal(Number(scheduledDeliveries[0]?.attempt_count ?? 0), 2);
    assert.equal(scheduledDeliveries[0]?.repository_item_id, outboundPayload.repositoryItemId);
    assert.equal(scheduledDeliveries[0]?.last_error_code, "http_503");

    const retryAuditRows = await prisma.$queryRaw<
      Array<{
        action: string;
      }>
    >`
      SELECT action
      FROM audit_logs
      WHERE law_firm_id = ${fixture.lawFirmId}
        AND action = 'kommo.delivery.retry_scheduled'
    `;

    assert.equal(retryAuditRows.length, 1);

    await prisma.$executeRaw`
      UPDATE kommo_outbound_deliveries
      SET next_retry_at = DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 MINUTE)
      WHERE law_firm_id = ${fixture.lawFirmId}
        AND id = ${outboundPayload.kommoDelivery?.deliveryId ?? ""}
    `;

    failWith503 = false;

    const bootstrapResponse = await app.inject({
      method: "GET",
      url: "/dashboard/bootstrap",
      headers: {
        cookie: `${env.COOKIE_NAME}=${encodeURIComponent(token)}`,
      },
    });

    assert.equal(bootstrapResponse.statusCode, 200);

    const bootstrapPayload = bootstrapResponse.json() as {
      summary: {
        kommoRetryScheduledCount: number;
        kommoFailedDeliveriesCount: number;
        kommoConversationsNeedingAttentionCount: number;
      };
    };

    assert.equal(bootstrapPayload.summary.kommoRetryScheduledCount, 0);
    assert.equal(bootstrapPayload.summary.kommoFailedDeliveriesCount, 0);
    assert.equal(bootstrapPayload.summary.kommoConversationsNeedingAttentionCount, 0);

    const recoveredMessages = await prisma.$queryRaw<
      Array<{
        message_status: string | null;
      }>
    >`
      SELECT message_status
      FROM messages
      WHERE law_firm_id = ${fixture.lawFirmId}
        AND repository_item_id = ${outboundPayload.repositoryItemId}
    `;

    assert.equal(recoveredMessages[0]?.message_status, "sent_via_kommo_salesbot");

    const recoveredDeliveries = await prisma.$queryRaw<
      Array<{
        status_code: string;
        attempt_count: number;
        delivered_at: Date | null;
      }>
    >`
      SELECT status_code, attempt_count, delivered_at
      FROM kommo_outbound_deliveries
      WHERE law_firm_id = ${fixture.lawFirmId}
        AND id = ${outboundPayload.kommoDelivery?.deliveryId ?? ""}
    `;

    assert.equal(recoveredDeliveries[0]?.status_code, "sent");
    assert.equal(Number(recoveredDeliveries[0]?.attempt_count ?? 0), 3);
    assert.ok(recoveredDeliveries[0]?.delivered_at);

    const successAuditRows = await prisma.$queryRaw<
      Array<{
        action: string;
      }>
    >`
      SELECT action
      FROM audit_logs
      WHERE law_firm_id = ${fixture.lawFirmId}
        AND action = 'kommo.delivery.retry_succeeded'
    `;

    assert.equal(successAuditRows.length, 1);
  } finally {
    globalThis.fetch = originalFetch;
    await app.close();
    await cleanupFixture(fixture);
  }
});
