// Test setup file for Vitest
import { vi, afterEach, beforeEach } from 'vitest'
import { config } from '@vue/test-utils'
import { readonly } from 'vue'

// Stub NODE_ENV before anything else
vi.stubEnv('NODE_ENV', 'test')

// Make readonly available globally for stores
global.readonly = readonly

// Mock $fetch globally
global.$fetch = vi.fn()

// Ensure process.env exists for Pinia
if (typeof process === 'undefined') {
  (globalThis as any).process = {
    env: {},
    client: true,
  }
}
if (!process.env) {
  process.env = {}
}
process.env.NODE_ENV = 'test'

// Mock import.meta for Nuxt 4+ (import.meta.client)
Object.defineProperty(import.meta, 'client', {
  value: true,
  writable: true,
  configurable: true,
})

Object.defineProperty(import.meta, 'server', {
  value: false,
  writable: true,
  configurable: true,
})

Object.defineProperty(import.meta, 'env', {
  value: {
    MODE: 'test',
    DEV: true,
    PROD: false,
    SSR: false,
  },
  writable: true,
  configurable: true,
})

// Create runtime config mock that will be used everywhere
const mockRuntimeConfig = {
  public: {
    leagueId: 'sba',
    leagueName: 'Stratomatic Baseball Association',
    apiUrl: 'http://localhost:8000',
    wsUrl: 'http://localhost:8000',
    discordClientId: 'test-client-id',
    discordRedirectUri: 'http://localhost:3000/auth/callback',
  },
}

// Make useRuntimeConfig available globally
global.useRuntimeConfig = vi.fn(() => mockRuntimeConfig)

// Mock Nuxt runtime config
vi.mock('#app', () => ({
  useRuntimeConfig: vi.fn(() => mockRuntimeConfig),
  useRouter: vi.fn(() => ({
    push: vi.fn(),
    replace: vi.fn(),
    back: vi.fn(),
  })),
  useRoute: vi.fn(() => ({
    params: {},
    query: {},
    path: '/',
  })),
  navigateTo: vi.fn(),
}))

// Mock localStorage
const localStorageMock = (() => {
  let store: Record<string, string> = {}

  return {
    getItem: (key: string) => store[key] || null,
    setItem: (key: string, value: string) => {
      store[key] = value.toString()
    },
    removeItem: (key: string) => {
      delete store[key]
    },
    clear: () => {
      store = {}
    },
  }
})()

global.localStorage = localStorageMock as Storage

// Mock Socket.io client
vi.mock('socket.io-client', () => ({
  io: vi.fn(() => ({
    on: vi.fn(),
    off: vi.fn(),
    emit: vi.fn(),
    connect: vi.fn(),
    disconnect: vi.fn(),
    connected: false,
    disconnected: true,
  })),
}))

// Configure Vue Test Utils
config.global.stubs = {
  // Stub Nuxt components if needed
}

// Clean up after each test
afterEach(() => {
  vi.clearAllMocks()
  localStorage.clear()
})
