import { describe, it, expect } from "vitest";
import {
  createScenePreset,
  isValidScenePreset,
} from "../../../src/contracts/scene-preset.js";
import { SCENE_PRESET_FIXTURES } from "../../fixtures/scene-preset.js";

describe("scene-preset contract", () => {
  describe("createScenePreset()", () => {
    it("creates a preset with required fields", () => {
      const p = createScenePreset("My Preset", { "user-1": "active" });
      expect(p.name).toBe("My Preset");
      expect(p.matrix).toEqual({ "user-1": "active" });
      expect(typeof p.createdAt).toBe("number");
      expect(typeof p.updatedAt).toBe("number");
      expect(p.createdAt).toBeGreaterThan(0);
    });

    it("creates a preset with empty matrix", () => {
      const p = createScenePreset("Empty", {});
      expect(p.matrix).toEqual({});
    });

    it("returns a shallow copy of the matrix", () => {
      const input = { "user-1": "active" };
      const p = createScenePreset("Test", input);
      input["user-1"] = "hidden";
      expect(p.matrix["user-1"]).toBe("active"); // not mutated
    });
  });

  describe("isValidScenePreset()", () => {
    it("accepts valid fixture", () => {
      expect(() => isValidScenePreset(SCENE_PRESET_FIXTURES.valid)).not.toThrow();
    });

    it("accepts empty matrix edge case", () => {
      expect(() => isValidScenePreset(SCENE_PRESET_FIXTURES.emptyMatrix)).not.toThrow();
    });

    it("throws on empty name", () => {
      expect(() => isValidScenePreset(SCENE_PRESET_FIXTURES.missingName)).toThrow(TypeError);
    });

    it("throws on wrong _version", () => {
      expect(() => isValidScenePreset(SCENE_PRESET_FIXTURES.wrongVersion)).toThrow(TypeError);
    });

    it("throws if not an object", () => {
      expect(() => isValidScenePreset(null)).toThrow(TypeError);
    });

    it("throws on unknown keys", () => {
      const bad = { ...SCENE_PRESET_FIXTURES.valid, extra: true };
      expect(() => isValidScenePreset(bad)).toThrow(TypeError);
    });

    it("throws on non-finite createdAt", () => {
      const bad = { ...SCENE_PRESET_FIXTURES.valid, createdAt: NaN };
      expect(() => isValidScenePreset(bad)).toThrow(TypeError);
    });

    it("throws on negative createdAt", () => {
      const bad = { ...SCENE_PRESET_FIXTURES.valid, createdAt: -1 };
      expect(() => isValidScenePreset(bad)).toThrow(TypeError);
    });

    it("throws on NaN updatedAt", () => {
      const bad = { ...SCENE_PRESET_FIXTURES.valid, updatedAt: NaN };
      expect(() => isValidScenePreset(bad)).toThrow(TypeError);
    });

    it("throws on Infinity updatedAt", () => {
      const bad = { ...SCENE_PRESET_FIXTURES.valid, updatedAt: Infinity };
      expect(() => isValidScenePreset(bad)).toThrow(TypeError);
    });
  });
});
