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

describe("activateChannel", () => {
  it("activates a draft Channel", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activated = {
      ...draftChannel,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    spies.select.mockReturnValueOnce(draftChannel).mockReturnValueOnce([draftChannel]);
    spies.update.mockReturnValueOnce(activated);

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

    expectOk(result);
  });

  it("throws when Channel is not in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseChannel);

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

    expectErr(result, InvalidChannelStatusError);
  });

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

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

    expectErr(result, ChannelNotFoundError);
  });

  it("throws when the draft channel is missing a supported type", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...draftChannel, type: "" });

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

    expectErr(result, InvalidChannelTypeError);
  });

  it("throws when another channel already uses the same name", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(draftChannel)
      .mockReturnValueOnce([
        draftChannel,
        { ...baseChannel, id: "channel-4", name: draftChannel.name },
      ]);

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

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