import type { Endpoint } from 'payload'

export const healthCheckEndpoint: Endpoint = {
  path: '/health-check',
  method: 'get',
  handler: async (req) => {
    try {
      // Check database connectivity by attempting a simple find on the users collection
      await req.payload.find({
        collection: 'users',
        limit: 1,
        depth: 0,
      })

      return Response.json({
        status: 'ok',
        timestamp: new Date().toISOString(),
        database: 'connected',
      })
    } catch (error) {
      req.payload.logger.error({
        err: error,
        msg: 'Health check failed',
      })

      return Response.json(
        {
          status: 'error',
          timestamp: new Date().toISOString(),
          database: 'disconnected',
        },
        { status: 500 },
      )
    }
  },
}
