import { describe, test, expect, vi, beforeEach } from 'vitest';
import { handleApiError } from '$lib/server/api/errorHandler';
import * as logger from '$lib/server/utils/logger';
import { ValidationError, NotFoundError, ConflictError } from '$lib/server/api/errors';

describe('errorHandler logging', () => {
  let logErrorSpy: any;

  beforeEach(() => {
    logErrorSpy = vi.spyOn(logger, 'logError').mockImplementation(() => {});
  });

  test('should use logError for standard errors', () => {
    const error = new Error('Test error');
    
    handleApiError(error);
    
    expect(logErrorSpy).toHaveBeenCalledWith('[API Error]', error);
  });

  test('should use logError for ValidationError', () => {
    const error = new ValidationError('Invalid input');
    
    const response = handleApiError(error);
    
    expect(logErrorSpy).toHaveBeenCalledWith('[API Error]', error);
    expect(response.status).toBe(400);
  });

  test('should use logError for NotFoundError', () => {
    const error = new NotFoundError('Resource not found');
    
    const response = handleApiError(error);
    
    expect(logErrorSpy).toHaveBeenCalledWith('[API Error]', error);
    expect(response.status).toBe(404);
  });

  test('should use logError for ConflictError', () => {
    const error = new ConflictError('Resource conflict');
    
    const response = handleApiError(error);
    
    expect(logErrorSpy).toHaveBeenCalledWith('[API Error]', error);
    expect(response.status).toBe(409);
  });

  test('should serialize complex error objects', () => {
    const complexError = {
      code: 'ERR_VALIDATION',
      message: 'Invalid input',
      details: { field: 'email', reason: 'invalid format' }
    };
    
    handleApiError(complexError);
    
    expect(logErrorSpy).toHaveBeenCalledWith('[API Error]', complexError);
  });

  test('should handle unknown error types', () => {
    const unknownError = 'String error';
    
    handleApiError(unknownError);
    
    expect(logErrorSpy).toHaveBeenCalledWith('[API Error]', unknownError);
  });

  test('logs should not use console.error directly', () => {
    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    
    const error = new Error('Test');
    handleApiError(error);
    
    // logError internally calls console.error, but handleApiError shouldn't call it directly
    // We're checking that handleApiError uses logError, not console.error
    expect(logErrorSpy).toHaveBeenCalledWith('[API Error]', error);
    
    consoleErrorSpy.mockRestore();
  });
});
