/**
 * API Error Handler
 *
 * Centralizes error handling for API endpoints by converting
 * application errors into appropriate HTTP responses.
 *
 * Maps error types to status codes:
 * - ValidationError → 400 Bad Request
 * - NotFoundError → 404 Not Found
 * - ConflictError → 409 Conflict
 * - Other errors → 500 Internal Server Error
 *
 * Provides consistent error response format across all API endpoints.
 */

import { json } from '@sveltejs/kit';
import { ValidationError, NotFoundError, ConflictError } from './errors';
import { logError } from '../utils/logger';

/**
 * Handle API errors and convert to appropriate HTTP responses
 *
 * @param error - Error to handle (can be any type)
 * @returns JSON response with appropriate status code and error message
 */
export function handleApiError(error: unknown): Response {
	// Log all errors for debugging
	logError('[API Error]', error);

	// Handle known error types with specific status codes
	if (error instanceof ValidationError) {
		return json(
			{
				message: error.message,
				type: 'validation_error'
			},
			{ status: 400 }
		);
	}

	if (error instanceof NotFoundError) {
		return json(
			{
				message: error.message,
				type: 'not_found_error'
			},
			{ status: 404 }
		);
	}

	if (error instanceof ConflictError) {
		return json(
			{
				message: error.message,
				type: 'conflict_error'
			},
			{ status: 409 }
		);
	}

	// Handle generic errors
	const message = error instanceof Error ? error.message : 'Unknown error occurred';

	// Don't expose internal error details in production
	const publicMessage = process.env.NODE_ENV === 'production' ? 'Internal server error' : message;

	return json(
		{
			message: publicMessage,
			type: 'server_error'
		},
		{ status: 500 }
	);
}
