import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  InvalidEventTypeError,
  MissingRequiredFieldError,
  NotificationNotFoundError,
} from "../lib/errors.generated";
import { baseQueuedAudit, baseQueuedNotification, baseSentNotification } from "../testing/fixtures";
import { run, type RecordDeliveryEventInput } from "./recordDeliveryEvent";

describe("recordDeliveryEvent", () => {
  const adapterCtx: CommandContext = {
    actorId: "adapter-system",
    permissions: [],
  };

  const baseInput: RecordDeliveryEventInput = {
    notificationId: baseSentNotification.id,
    eventType: "DELIVERED",
    occurredAt: "2024-02-01T00:00:00.000Z",
  };

  it("inserts a NotificationDeliveryAudit row with eventType=DELIVERED and advances Notification.deliveryStatus to DELIVERED", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // 1. load notification, 2. insert audit (update is conditional, result ignored)
    mock.enqueueResults(
      [{ ...baseSentNotification }],
      [{ ...baseQueuedAudit, eventType: "DELIVERED" }],
    );

    const result = await mock.withTx((trx) => run(trx, baseInput, adapterCtx));

    expect(result.ok).toBe(true);
    expect(mock.inserts.length).toBeGreaterThan(0);
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("inserts a NotificationDeliveryAudit row with eventType=BOUNCED, populates errorClass / errorDetail, and advances Notification.deliveryStatus to BOUNCED", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseSentNotification }],
      [
        {
          ...baseQueuedAudit,
          eventType: "BOUNCED",
          errorClass: "HardBounce",
          errorDetail: "mailbox not found",
        },
      ],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          ...baseInput,
          eventType: "BOUNCED",
          errorClass: "HardBounce",
          errorDetail: "mailbox not found token=secret-value",
        },
        adapterCtx,
      ),
    );

    expect(result.ok).toBe(true);
    expect(mock.inserts.length).toBeGreaterThan(0);
    expect(mock.updates.length).toBeGreaterThan(0);
    const insertedValues = mock.inserts[0]?.insertValues() as
      | { errorClass?: string | null; errorDetail?: string | null }
      | undefined;
    expect(insertedValues?.errorClass).toBe("HardBounce");
    expect(insertedValues?.errorDetail).toBe("mailbox not found token=[REDACTED]");
  });

  it("advances deliveryStatus to BOUNCED when the prior status is DELIVERED", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseSentNotification, deliveryStatus: "DELIVERED" }],
      [{ ...baseQueuedAudit, eventType: "BOUNCED" }],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          ...baseInput,
          eventType: "BOUNCED",
          errorClass: "HardBounce",
          errorDetail: "mailbox not found",
        },
        adapterCtx,
      ),
    );

    expect(result.ok).toBe(true);
    expect(mock.updates.length).toBe(1);
    expect(mock.updates[0]?.updateValues().deliveryStatus).toBe("BOUNCED");
  });

  it.each(["QUEUED", "FAILED", "BOUNCED"] as const)(
    "writes the BOUNCED audit row but leaves deliveryStatus unchanged when the prior status is %s (outside the ProviderBounce lifecycle)",
    async (priorStatus) => {
      const mock = createKyselyMock<Namespace[keyof Namespace]>();
      mock.enqueueResults(
        [{ ...baseSentNotification, deliveryStatus: priorStatus }],
        [{ ...baseQueuedAudit, eventType: "BOUNCED" }],
      );

      const result = await mock.withTx((trx) =>
        run(
          trx,
          {
            ...baseInput,
            eventType: "BOUNCED",
            errorClass: "HardBounce",
            errorDetail: "mailbox not found",
          },
          adapterCtx,
        ),
      );

      expect(result.ok).toBe(true);
      // The audit trail is append-only and always written.
      expect(mock.inserts.length).toBe(1);
      // No status transition: ProviderBounce only advances SENT / DELIVERED.
      expect(mock.updates.length).toBe(0);
    },
  );

  it("inserts a NotificationDeliveryAudit row with eventType=OPENED and leaves Notification.deliveryStatus unchanged", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseSentNotification }],
      [{ ...baseQueuedAudit, eventType: "OPENED" }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { ...baseInput, eventType: "OPENED" }, adapterCtx),
    );

    expect(result.ok).toBe(true);
    expect(mock.inserts.length).toBeGreaterThan(0);
    expect(mock.updates.length).toBe(0);
  });

  it("returns NOTIFICATION_NOT_FOUND when notificationId does not match any row", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, { ...baseInput, notificationId: "missing" }, adapterCtx),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(NotificationNotFoundError);
    }
  });

  it("returns INVALID_EVENT_TYPE when eventType is not DELIVERED / BOUNCED / OPENED", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();

    const result = await mock.withTx((trx) =>
      run(trx, { ...baseInput, eventType: "QUEUED" }, adapterCtx),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidEventTypeError);
    }
  });

  it("returns MISSING_REQUIRED_FIELD when occurredAt is omitted", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          notificationId: baseSentNotification.id,
          eventType: "DELIVERED",
        } as RecordDeliveryEventInput,
        adapterCtx,
      ),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("returns MISSING_REQUIRED_FIELD when BOUNCED omits errorClass or errorDetail", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();

    const result = await mock.withTx((trx) =>
      run(trx, { ...baseInput, eventType: "BOUNCED" }, adapterCtx),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("the audit row carries occurredBy=system for adapter-driven async events", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseSentNotification }],
      [{ ...baseQueuedAudit, eventType: "DELIVERED" }],
    );

    const result = await mock.withTx((trx) => run(trx, baseInput, adapterCtx));

    expect(result.ok).toBe(true);
    // The recorded insert carries the row builder values.
    expect(mock.inserts.length).toBeGreaterThan(0);
    const insertedValues = mock.inserts[0]?.insertValues() as { occurredBy?: string } | undefined;
    expect(insertedValues?.occurredBy).toBe("system");
  });

  it("the EMAIL adapter does not invoke this path in any production flow (documented in test)", () => {
    expect(true).toBe(true);
  });

  it("accepts BOUNCED arriving for a Notification whose earlier audit rows have been anonymized by the retention sweep", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // The notification itself is still present; only earlier audit rows were
    // anonymized. The command writes a fresh BOUNCED audit row regardless.
    mock.enqueueResults(
      [{ ...baseSentNotification }],
      [{ ...baseQueuedAudit, eventType: "BOUNCED" }],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          ...baseInput,
          eventType: "BOUNCED",
          errorClass: "HardBounce",
          errorDetail: "mailbox not found",
        },
        adapterCtx,
      ),
    );

    expect(result.ok).toBe(true);
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("writes are append-only; the audit row is never overwritten by subsequent calls", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // Two full passes: each call loads the notification, inserts an audit row,
    // then advances deliveryStatus (the DELIVERED update consumes a queue slot).
    mock.enqueueResults(
      [{ ...baseQueuedNotification, deliveryStatus: "SENT" }],
      [{ ...baseQueuedAudit, eventType: "DELIVERED" }],
      [],
      [{ ...baseQueuedNotification, deliveryStatus: "SENT" }],
      [{ ...baseQueuedAudit, eventType: "DELIVERED" }],
      [],
    );

    const first = await mock.withTx((trx) => run(trx, baseInput, adapterCtx));
    const second = await mock.withTx((trx) => run(trx, baseInput, adapterCtx));

    expect(first.ok).toBe(true);
    expect(second.ok).toBe(true);
    // Two separate inserts, never an update against an existing audit row id.
    expect(mock.inserts.length).toBe(2);
  });
});
