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

describe("activateChannel", () => {
  it("activates a draft Channel", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activated = {
      ...draftChannel,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    mock.enqueueResults([draftChannel], [draftChannel], [activated]);

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

    expectOk(result);
  });

  it("throws when Channel is not in DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannel]);

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

    expectErr(result, InvalidChannelStatusError);
  });

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

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

    expectErr(result, ChannelNotFoundError);
  });

  it("throws when the draft channel is missing a supported type", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...draftChannel, type: "" }]);

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

    expectErr(result, InvalidChannelTypeError);
  });

  it("throws when another channel already uses the same name", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [draftChannel],
      [draftChannel, { ...baseChannel, id: "channel-4", name: draftChannel.name }],
    );

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

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