// Vitest 测试环境初始化
// 依据：vitest.config.ts setupFiles

import { beforeEach, afterEach } from "vitest";
import "@testing-library/jest-dom/vitest";
import { server } from "../mocks/server";
import { handlers } from "../mocks/handlers";

// jsdom 环境补充：matchMedia（recharts 等库依赖）
if (!window.matchMedia) {
  Object.defineProperty(window, "matchMedia", {
    writable: true,
    value: (query: string): MediaQueryList => ({
      matches: false,
      media: query,
      onchange: null,
      addListener: () => {},
      removeListener: () => {},
      addEventListener: () => {},
      removeEventListener: () => {},
      dispatchEvent: () => false,
    }),
  });
}

// jsdom 环境补充：IntersectionObserver
if (!window.IntersectionObserver) {
  class MockIntersectionObserver {
    observe(): void {}
    unobserve(): void {}
    disconnect(): void {}
    takeRecords(): IntersectionObserverEntry[] {
      return [];
    }
  }
  Object.defineProperty(window, "IntersectionObserver", {
    writable: true,
    value: MockIntersectionObserver,
  });
}

// jsdom 环境补充：ResizeObserver（recharts 依赖）
if (!window.ResizeObserver) {
  class MockResizeObserver {
    observe(): void {}
    unobserve(): void {}
    disconnect(): void {}
  }
  Object.defineProperty(window, "ResizeObserver", {
    writable: true,
    value: MockResizeObserver,
  });
}

// 清理 localStorage
beforeEach(() => {
  localStorage.clear();
  sessionStorage.clear();
});

// 全局恢复 MSW 初始 handlers（防止测试间隔离问题）
// 某些测试文件使用 server.resetHandlers(...newHandlers) 会替换初始 handlers，
// 此处显式恢复原始 handlers，确保后续测试文件的请求能被正确拦截
afterEach(() => {
  server.resetHandlers(...handlers);
});
