import { afterEach, describe, expect, it } from "../test/testHarness";

import {
  __resetGenerationConcurrencyForTests,
  claimGenerationSlot,
  getActiveGenerationTaskCount,
  getEffectiveGenerationLimit,
  getGenerationUserKey,
  releaseGenerationSlot,
  setUserMaxConcurrency,
} from "./generationConcurrency";

describe("generationConcurrency", () => {
  afterEach(() => {
    __resetGenerationConcurrencyForTests();
  });

  it("uses the default generation limit until the server provides a user-specific limit", () => {
    expect(getEffectiveGenerationLimit()).toBe(3);

    setUserMaxConcurrency(5);
    expect(getEffectiveGenerationLimit()).toBe(5);

    setUserMaxConcurrency(0);
    expect(getEffectiveGenerationLimit()).toBe(3);
  });

  it("claims and releases local generation slots so the submit button can recover", () => {
    const userKey = getGenerationUserKey("user-1");

    const releaseFirst = claimGenerationSlot({
      userKey,
      kind: "image",
      id: "slot-1",
    });
    claimGenerationSlot({ userKey, kind: "video", id: "slot-2" });

    expect(getActiveGenerationTaskCount(userKey)).toBe(2);

    releaseFirst();
    expect(getActiveGenerationTaskCount(userKey)).toBe(1);

    releaseGenerationSlot("slot-2");
    expect(getActiveGenerationTaskCount(userKey)).toBe(0);
  });

  it("enforces per-user limits without blocking other users", () => {
    setUserMaxConcurrency(1);

    claimGenerationSlot({ userKey: "alice", kind: "image", id: "alice-slot" });

    expect(() =>
      claimGenerationSlot({
        userKey: "alice",
        kind: "video",
        id: "alice-slot-2",
      }),
    ).toThrow("最多生成 1 个图片/视频任务");
    expect(() =>
      claimGenerationSlot({ userKey: "bob", kind: "video", id: "bob-slot" }),
    ).not.toThrow();
  });
});
