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 { NotDeliveredError, NotificationNotFoundError } from "../lib/errors.generated";
import {
  baseArchivedNotification,
  baseDeliveredNotification,
  baseReadNotification,
  baseSentNotification,
} from "../testing/fixtures";
import { run } from "./archiveNotification";

const ctx: CommandContext = { actorId: "user-1", permissions: [] };

describe("archiveNotification", () => {
  it("adds ARCHIVED to engagementStatuses on a caller-owned Notification and stamps archivedAt", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseSentNotification }],
      [{ ...baseSentNotification, engagementStatuses: ["ARCHIVED"] }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { notificationId: baseSentNotification.id }, ctx),
    );

    expect(result.ok).toBe(true);
    const setCall = mock.updates[0]?.updateValues();
    expect(setCall.engagementStatuses).toEqual(["ARCHIVED"]);
    expect(setCall.archivedAt).toBeInstanceOf(Date);
  });

  it("does not auto-add READ when archiving an unread Notification", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseSentNotification }],
      [{ ...baseSentNotification, engagementStatuses: ["ARCHIVED"] }],
    );

    await mock.withTx((trx) => run(trx, { notificationId: baseSentNotification.id }, ctx));

    const setCall = mock.updates[0]?.updateValues();
    expect(setCall.engagementStatuses).not.toContain("READ");
  });

  it("adds ARCHIVED to a Notification already containing READ, resulting in engagementStatuses of {SEEN, READ, ARCHIVED}", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseReadNotification }],
      [{ ...baseReadNotification, engagementStatuses: ["SEEN", "READ", "ARCHIVED"] }],
    );

    await mock.withTx((trx) => run(trx, { notificationId: baseReadNotification.id }, ctx));

    const setCall = mock.updates[0]?.updateValues();
    expect(setCall.engagementStatuses).toEqual(["SEEN", "READ", "ARCHIVED"]);
  });

  it("returns the existing row unchanged when ARCHIVED is already present (idempotent), without re-stamping archivedAt", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseArchivedNotification }]);

    const result = await mock.withTx((trx) =>
      run(trx, { notificationId: baseArchivedNotification.id }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.notification.archivedAt).toEqual(baseArchivedNotification.archivedAt);
    }
    expect(mock.updates.length).toBe(0);
  });

  it("returns NOTIFICATION_NOT_FOUND when the Notification's recipientUserId is a different user (no existence oracle)", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseSentNotification, recipientUserId: "user-2" }]);

    const result = await mock.withTx((trx) =>
      run(trx, { notificationId: baseSentNotification.id }, ctx),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      // Same error as the missing-row case: existence is not disclosed.
      expect(result.error).toBeInstanceOf(NotificationNotFoundError);
    }
  });

  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, { notificationId: "missing" }, ctx));

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

  it("returns NOT_DELIVERED when deliveryStatus is QUEUED", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseSentNotification, deliveryStatus: "QUEUED" }]);

    const result = await mock.withTx((trx) =>
      run(trx, { notificationId: baseSentNotification.id }, ctx),
    );

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

  it("returns NOT_DELIVERED when deliveryStatus is FAILED", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseSentNotification, deliveryStatus: "FAILED" }]);

    const result = await mock.withTx((trx) =>
      run(trx, { notificationId: baseSentNotification.id }, ctx),
    );

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

  it("returns NOT_DELIVERED when deliveryStatus is BOUNCED", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseSentNotification, deliveryStatus: "BOUNCED" }]);

    const result = await mock.withTx((trx) =>
      run(trx, { notificationId: baseSentNotification.id }, ctx),
    );

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

  it("excludes the row from the default inbox feed after archiving", async () => {
    // Behavior verified by listInboxNotifications: rows with ARCHIVED in
    // engagementStatuses are excluded from the default feed.
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseDeliveredNotification }],
      [{ ...baseDeliveredNotification, engagementStatuses: ["ARCHIVED"] }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { notificationId: baseDeliveredNotification.id }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.notification.engagementStatuses).toContain("ARCHIVED");
    }
  });

  it("excludes the row from unreadCount after archiving regardless of READ presence", async () => {
    // Behavior verified by listInboxNotifications: the unread predicate excludes
    // rows containing ARCHIVED, so archiving any row removes it from unreadCount.
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseSentNotification }],
      [{ ...baseSentNotification, engagementStatuses: ["ARCHIVED"] }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { notificationId: baseSentNotification.id }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.notification.engagementStatuses).toContain("ARCHIVED");
      expect(result.value.notification.engagementStatuses).not.toContain("READ");
    }
  });

  it("writes a NotificationDeliveryAudit row with eventType=ARCHIVED and occurredBy=recipientUserId on the first transition", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseSentNotification }],
      [{ ...baseSentNotification, engagementStatuses: ["ARCHIVED"] }],
    );

    await mock.withTx((trx) => run(trx, { notificationId: baseSentNotification.id }, ctx));

    const auditValues = mock.inserts[0]?.insertValues();
    expect(auditValues.eventType).toBe("ARCHIVED");
    expect(auditValues.occurredBy).toBe(baseSentNotification.recipientUserId);
    expect(auditValues.notificationId).toBe(baseSentNotification.id);
  });
});
