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 { ChannelNotFoundError, MissingRequiredFieldError } from "../lib/errors.generated";
import { baseEmailChannel } from "../testing/fixtures";
import { run } from "./updateNotificationChannel";

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

const validCapabilities = {
  supportsHtmlBody: true,
  supportsAttachments: true,
  supportsRichActions: false,
};

describe("updateNotificationChannel", () => {
  it("updates the displayName on an existing NotificationChannel row", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // 1. load channel, 2. update channel
    mock.enqueueResults(
      [{ ...baseEmailChannel }],
      [{ ...baseEmailChannel, displayName: "Email (SendGrid)" }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { channelId: "EMAIL", displayName: "Email (SendGrid)" }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.channel.displayName).toBe("Email (SendGrid)");
    }
    expect(mock.updates[0]?.updateValues()).toEqual(
      expect.objectContaining({ displayName: "Email (SendGrid)" }),
    );
  });

  it("updates the capabilities object on an existing NotificationChannel row", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseEmailChannel }],
      [{ ...baseEmailChannel, capabilities: validCapabilities }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { channelId: "EMAIL", capabilities: validCapabilities }, ctx),
    );

    expect(result.ok).toBe(true);
    expect(mock.updates[0]?.updateValues()).toEqual(
      expect.objectContaining({ capabilities: validCapabilities }),
    );
  });

  it("leaves enabled unchanged when only displayName / capabilities are supplied", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseEmailChannel, enabled: true }],
      [{ ...baseEmailChannel, displayName: "New name" }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { channelId: "EMAIL", displayName: "New name" }, ctx),
    );

    expect(result.ok).toBe(true);
    const setArg = mock.updates[0]?.updateValues() as Record<string, unknown> | undefined;
    expect(setArg).toBeDefined();
    expect(setArg).not.toHaveProperty("enabled");
  });

  it("leaves kind unchanged regardless of which fields are supplied", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseEmailChannel }],
      [{ ...baseEmailChannel, displayName: "New name", capabilities: validCapabilities }],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { channelId: "EMAIL", displayName: "New name", capabilities: validCapabilities },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    const setArg = mock.updates[0]?.updateValues() as Record<string, unknown> | undefined;
    expect(setArg).toBeDefined();
    expect(setArg).not.toHaveProperty("kind");
  });

  it("returns CHANNEL_NOT_FOUND when the channelId does not exist", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, { channelId: "EMAIL", displayName: "Anything" }, ctx),
    );

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

  it("returns MISSING_REQUIRED_FIELD when the supplied displayName is blank", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseEmailChannel }]);

    const result = await mock.withTx((trx) =>
      run(trx, { channelId: "EMAIL", displayName: "   " }, ctx),
    );

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

  it("returns MISSING_REQUIRED_FIELD when the supplied capabilities object is missing supportsHtmlBody", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseEmailChannel }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          channelId: "EMAIL",
          capabilities: {
            supportsAttachments: true,
            supportsRichActions: false,
          } as unknown as typeof validCapabilities,
        },
        ctx,
      ),
    );

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

  it("subsequent dispatches read the new capabilities and already-persisted Notifications are not mutated", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseEmailChannel }],
      [{ ...baseEmailChannel, capabilities: validCapabilities }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { channelId: "EMAIL", capabilities: validCapabilities }, ctx),
    );

    expect(result.ok).toBe(true);
    // The command updates only NotificationChannel rows; it never touches Notification rows.
    expect(mock.updates.length).toBe(1);
  });
});
