import { describe, it, expect, beforeEach } from "vitest";
import { mount } from "@vue/test-utils";
import { setActivePinia, createPinia } from "pinia";
import { useAreasStore } from "../../stores/areas.js";
import AreaTreePage from "../../features/areas/pages/AreaTreePage.vue";

describe("Area lifecycle integration", () => {
  beforeEach(() => {
    setActivePinia(createPinia());
  });

  it("loads areas on mount", async () => {
    const wrapper = mount(AreaTreePage);

    await new Promise((resolve) => setTimeout(resolve, 50));

    const store = useAreasStore();
    expect(store.areas.length).toBe(2);
    expect(store.areas[0].display_name).toBe("Kitchen");
  });

  it("creates a new area and adds it to the list", async () => {
    const wrapper = mount(AreaTreePage);
    await new Promise((resolve) => setTimeout(resolve, 50));

    const store = useAreasStore();
    const initialCount = store.areas.length;

    await store.createArea({ type: "room", alias: "bedroom", display_name: "Bedroom" });

    expect(store.areas.length).toBe(initialCount + 1);
    expect(store.areas.find((a) => a.alias === "bedroom")).toBeDefined();
  });

  it("renames an existing area", async () => {
    const wrapper = mount(AreaTreePage);
    await new Promise((resolve) => setTimeout(resolve, 50));

    const store = useAreasStore();
    const area = store.areas[0];

    await store.renameArea(area.id, "Updated Name");

    expect(store.areas[0].display_name).toBe("Updated Name");
  });

  it("removes an area from the list", async () => {
    const wrapper = mount(AreaTreePage);
    await new Promise((resolve) => setTimeout(resolve, 50));

    const store = useAreasStore();
    const area = store.areas[0];

    await store.removeArea(area.id);

    expect(store.areas.find((a) => a.id === area.id)).toBeUndefined();
  });
});
