// Copyright 2025 Northern.tech AS
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
import handlers from '@northern.tech/testing/requestHandlers/requestHandlers';
import { afterAll as ntAfterAll, afterEach as ntAfterEach, beforeAll as ntBeforeAll, beforeEach as ntBeforeEach } from '@northern.tech/testing/setupTests';
import '@testing-library/jest-dom/vitest';
import { setupServer } from 'msw/node';
import { afterAll, afterEach, beforeAll, beforeEach, vi } from 'vitest';

process.on('unhandledRejection', err => {
  throw err;
});

// Setup requests interception
const server = setupServer(...handlers);

// ensure consistent snapshots across dev machines and CI
// - module loading order prevents this from fitting into the regular hooks
Object.defineProperty(process, 'platform', { value: 'linux', writable: true });

Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: vi.fn().mockImplementation(function (query) {
    return {
      matches: false,
      media: query,
      onchange: null,
      addListener: vi.fn(),
      removeListener: vi.fn(),
      addEventListener: vi.fn(),
      removeEventListener: vi.fn(),
      dispatchEvent: vi.fn()
    };
  })
});

beforeAll(async () => {
  await server.listen({ onUnhandledRequest: 'error' });
  await ntBeforeAll({ expect, vi });
});

beforeEach(async () => {
  await ntBeforeEach({ vi });
});

afterEach(async () => {
  await ntAfterEach({ vi });
  // Reset any runtime handlers tests may use.
  await server.resetHandlers();
});

afterAll(async () => {
  // Clean up once the tests are done.
  await server.close();
  await ntAfterAll({ vi });
});
