import { Context } from 'hono';
import { getLogger } from '@stock-bot/logger';
import { ApiResponse } from '../types/exchange.types';
import { ValidationError } from './validation';

const logger = getLogger('error-handler');

export function handleError(c: Context, error: unknown, operation: string): Response {
  logger.error(`Failed ${operation}`, { error });

  // Handle validation errors
  if (error instanceof ValidationError) {
    const response: ApiResponse = {
      success: false,
      error: error.message,
    };
    return c.json(response, 400);
  }

  // Handle database constraint violations
  if (error instanceof Error && error.message.includes('duplicate key')) {
    const response: ApiResponse = {
      success: false,
      error: 'Resource already exists with this unique identifier',
    };
    return c.json(response, 409);
  }

  // Handle not found errors
  if (error instanceof Error && error.message.includes('not found')) {
    const response: ApiResponse = {
      success: false,
      error: error.message,
    };
    return c.json(response, 404);
  }

  // Generic error response
  const response: ApiResponse = {
    success: false,
    error: error instanceof Error ? error.message : 'Unknown error occurred',
  };
  return c.json(response, 500);
}

export function createSuccessResponse<T>(
  data: T,
  message?: string,
  total?: number
): ApiResponse<T> {
  const response: ApiResponse<T> = {
    success: true,
    data,
  };

  if (message) {
    response.message = message;
  }
  if (total !== undefined) {
    response.total = total;
  }

  return response;
}
