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,
  baseFailedNotification,
  baseQueuedNotification,
  baseReadNotification,
  baseSeenNotification,
  baseSentNotification,
} from "../testing/fixtures";
import { run } from "./markNotificationAsRead";

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

describe("markNotificationAsRead", () => {
  it("adds READ (and SEEN if absent) to engagementStatuses on a SENT Notification owned by the caller and stamps readAt", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseSentNotification }],
      [
        {
          ...baseSentNotification,
          engagementStatuses: ["SEEN", "READ"],
        },
      ],
    );

    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(["SEEN", "READ"]);
    expect(setCall.seenAt).toBeInstanceOf(Date);
    expect(setCall.readAt).toBeInstanceOf(Date);
  });

  it("adds SEEN alongside READ when SEEN was not previously present", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseDeliveredNotification, engagementStatuses: [] }],
      [
        {
          ...baseDeliveredNotification,
          engagementStatuses: ["SEEN", "READ"],
        },
      ],
    );

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

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

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

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

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

  it("returns the existing row unchanged when the row is ARCHIVED (idempotent), even if READ is absent", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([
      { ...baseArchivedNotification, engagementStatuses: ["SEEN", "ARCHIVED"] },
    ]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.notification.engagementStatuses).not.toContain("READ");
    }
    expect(mock.updates.length).toBe(0);
    expect(mock.inserts.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([{ ...baseQueuedNotification }]);

    const result = await mock.withTx((trx) =>
      run(trx, { notificationId: baseQueuedNotification.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([{ ...baseFailedNotification }]);

    const result = await mock.withTx((trx) =>
      run(trx, { notificationId: baseFailedNotification.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([{ ...baseQueuedNotification, deliveryStatus: "BOUNCED" }]);

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

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

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

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

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

  it("decrements the unreadCount returned by the inbox feed query on the next call", async () => {
    // Behavior verified by the inbox feed query: the row no longer satisfies the
    // unread predicate (READ is in engagementStatuses) once this command succeeds.
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseSentNotification }],
      [
        {
          ...baseSentNotification,
          engagementStatuses: ["SEEN", "READ"],
        },
      ],
    );

    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("READ");
    }
  });
});
