import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  ChannelNotFoundError,
  DuplicateChannelNameError,
  InvalidChannelTypeError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { baseChannel } from "../testing/fixtures";
import { run } from "./updateChannel";

describe("updateChannel", () => {
  it("updates mutable Channel fields", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = {
      ...baseChannel,
      name: "Marketplace EU",
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    mock.enqueueResults([baseChannel], [], [updated]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { channelId: baseChannel.id, name: "Marketplace EU", settings: { region: "EU" } },
        commandCtx,
      ),
    );

    expectOk(result);
  });

  it("returns error when Channel does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, { channelId: baseChannel.id, name: "Marketplace EU" }, commandCtx),
    );

    expectErr(result, ChannelNotFoundError);
  });

  it("returns error when the resulting channel type is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannel]);

    const result = await mock.withTx((trx) =>
      run(trx, { channelId: baseChannel.id, type: "" }, commandCtx),
    );

    expectErr(result, InvalidChannelTypeError);
  });

  it("returns error when the updated channel name conflicts within the company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseChannel],
      [{ ...baseChannel, id: "channel-2", name: "Marketplace EU" }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { channelId: baseChannel.id, name: "Marketplace EU" }, commandCtx),
    );

    expectErr(result, DuplicateChannelNameError);
  });
});
