import { describe, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ChannelNotEditableError,
  ChannelNotFoundError,
  DuplicateChannelNameError,
  InvalidChannelTypeError,
} from "../lib/errors.generated";
import { baseChannel } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./updateChannel";

describe("updateChannel", () => {
  it("updates mutable Channel fields", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = {
      ...baseChannel,
      name: "Marketplace EU",
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    spies.select.mockReturnValueOnce(baseChannel).mockReturnValueOnce([]);
    spies.update.mockReturnValueOnce(updated);

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

    expectOk(result);
  });

  it("returns error when Channel does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

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

    expectErr(result, ChannelNotFoundError);
  });

  it("returns error when Channel is not editable", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseChannel, status: "ARCHIVED" });

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

    expectErr(result, ChannelNotEditableError);
  });

  it("returns error when the resulting channel type is empty", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseChannel);

    const result = await run(db, { channelId: baseChannel.id, type: "" }, commandCtx);

    expectErr(result, InvalidChannelTypeError);
  });

  it("returns error when the updated channel name conflicts within the company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseChannel)
      .mockReturnValueOnce([{ ...baseChannel, id: "channel-2", name: "Marketplace EU" }]);

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

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