/**
 * Jest Test Setup
 *
 * Global test configuration and environment setup for all test suites.
 * This file runs before all tests.
 */

// Set test environment
process.env.NODE_ENV = 'test';

// Set test config values
process.env.JWT_ACCESS_SECRET = 'test-access-secret';
process.env.JWT_REFRESH_SECRET = 'test-refresh-secret';
process.env.JWT_ACCESS_EXPIRES = '15m';
process.env.JWT_REFRESH_EXPIRES = '7d';
process.env.DB_HOST = 'localhost';
process.env.DB_PORT = '5432';
process.env.DB_NAME = 'test_db';
process.env.DB_USER = 'test_user';
process.env.DB_PASSWORD = 'test_password';
process.env.FRONTEND_URL = 'http://localhost:3000';
process.env.EMAIL_HOST = 'smtp.test.com';
process.env.EMAIL_PORT = '587';
process.env.EMAIL_FROM = 'test@test.com';

// Configure test timeouts
jest.setTimeout(10000); // 10 seconds

// Mock logger to prevent console spam during tests
jest.mock('../shared/utils/logger', () => ({
  logger: {
    info: jest.fn(),
    error: jest.fn(),
    warn: jest.fn(),
    debug: jest.fn(),
  },
}));

// Global test utilities
global.testUtils = {
  /**
   * Generate a valid test email
   */
  generateTestEmail: () => `test-${Date.now()}@example.com`,

  /**
   * Generate a strong test password
   */
  generateTestPassword: () => 'TestPass123!',

  /**
   * Create a mock user object
   */
  createMockUser: (overrides = {}) => ({
    id: 'test-user-id',
    email: 'test@example.com',
    emailVerified: true,
    phoneVerified: false,
    primaryAuthProvider: 'email' as const,
    totpEnabled: false,
    role: 'investor' as const,
    status: 'active' as const,
    failedLoginAttempts: 0,
    createdAt: new Date(),
    updatedAt: new Date(),
    ...overrides,
  }),

  /**
   * Create a mock profile object
   */
  createMockProfile: (overrides = {}) => ({
    id: 'test-profile-id',
    userId: 'test-user-id',
    firstName: 'John',
    lastName: 'Doe',
    displayName: 'John Doe',
    timezone: 'UTC',
    language: 'en',
    preferredCurrency: 'USD',
    ...overrides,
  }),

  /**
   * Create a mock session object
   */
  createMockSession: (overrides = {}) => ({
    id: 'test-session-id',
    userId: 'test-user-id',
    refreshToken: 'mock-refresh-token',
    userAgent: 'Mozilla/5.0',
    ipAddress: '127.0.0.1',
    expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
    createdAt: new Date(),
    lastActiveAt: new Date(),
    ...overrides,
  }),
};

// Declare global TypeScript types
declare global {
  // eslint-disable-next-line no-var
  var testUtils: {
    generateTestEmail: () => string;
    generateTestPassword: () => string;
    createMockUser: (overrides?: Record<string, unknown>) => Record<string, unknown>;
    createMockProfile: (overrides?: Record<string, unknown>) => Record<string, unknown>;
    createMockSession: (overrides?: Record<string, unknown>) => Record<string, unknown>;
  };
}

// Clean up after all tests
afterAll(() => {
  jest.clearAllMocks();
});
