import fp from 'fastify-plugin'
import { AppError, ValidationError } from '../lib/errors.js'

export const errorHandlerPlugin = fp(async (app) => {
  app.setErrorHandler((error: Error & { statusCode?: number; stack?: string }, request, reply) => {
    // Use AppError statusCode if available, else Fastify's, else 500
    const statusCode = error instanceof AppError
      ? error.statusCode
      : (error.statusCode ?? 500)

    // Only log 5xx as errors, 4xx as warnings
    const logData = {
      err: statusCode >= 500 ? error : undefined,
      statusCode,
      url: request.url,
      method: request.method,
      requestId: request.id,
      message: error.message,
    }

    if (statusCode >= 500) {
      request.log.error(logData)
    } else {
      request.log.warn(logData)
    }

    const response: Record<string, unknown> = {
      error: {
        message: statusCode >= 500 ? 'Internal Server Error' : error.message,
        statusCode,
      },
    }

    // Include validation details in non-production
    if (error instanceof ValidationError && error.details) {
      (response.error as Record<string, unknown>).details = error.details
    }

    // Stack trace only in development
    if (process.env.NODE_ENV === 'development' && statusCode >= 500) {
      (response.error as Record<string, unknown>).stack = error.stack
    }

    reply.status(statusCode).send(response)
  })

  app.setNotFoundHandler((request, reply) => {
    reply.status(404).send({
      error: {
        message: `Route ${request.method} ${request.url} not found`,
        statusCode: 404,
      },
    })
  })
})
