import { Request, Response, NextFunction } from 'express'
import { AppError } from './index'

export function errorMiddleware(err: any, _req: Request, res: Response, _next: NextFunction) {
  if (err.name === 'ZodError') {
    return res.status(400).json({ error: 'validation_error', message: 'Invalid request body', issues: err.issues, statusCode: 400 })
  }

  if (err.code === 'P2025') {
    return res.status(404).json({ error: 'not_found', message: 'Resource not found', statusCode: 404 })
  }

  if (err.code === 'P2002') {
    return res.status(409).json({ error: 'conflict', message: 'A resource with this value already exists', statusCode: 409 })
  }

  if (err instanceof AppError) {
    if (err.statusCode >= 500) console.error('[API Error]', err)
    return res.status(err.statusCode).json({ error: err.error, message: err.message, statusCode: err.statusCode, ...err.data })
  }

  const statusCode = err.statusCode ?? 500
  const message    = err.message ?? 'Internal server error'
  const code       = err.code ?? 'internal_error'

  if (statusCode >= 500) console.error('[API Error]', err)

  res.status(statusCode).json({ error: code, message, statusCode })
}
