import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';

import { prisma } from '@hexahost/database';
import { getConfig } from '@hexahost/config';

import { logger } from './logger';

export function startHealthServer(): ReturnType<typeof createServer> {
  const config = getConfig();

  const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
    if (req.url !== '/health' && req.url !== '/health/ready') {
      res.writeHead(404, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ status: 'error', message: 'Not found' }));
      return;
    }

    const isReady = req.url === '/health/ready';
    const timestamp = new Date().toISOString();

    if (!isReady) {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(
        JSON.stringify({
          status: 'ok',
          service: config.APP_NAME,
          timestamp,
        }),
      );
      return;
    }

    try {
      await prisma.$queryRaw`SELECT 1`;
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(
        JSON.stringify({
          status: 'ok',
          service: config.APP_NAME,
          timestamp,
          checks: [{ name: 'database', status: 'ok' }],
        }),
      );
    } catch (error) {
      logger.error({ err: error }, 'Readiness check failed');
      res.writeHead(503, { 'Content-Type': 'application/json' });
      res.end(
        JSON.stringify({
          status: 'error',
          service: config.APP_NAME,
          timestamp,
          checks: [
            {
              name: 'database',
              status: 'error',
              message: error instanceof Error ? error.message : 'Database check failed',
            },
          ],
        }),
      );
    }
  });

  server.listen(config.WORKER_PORT, '0.0.0.0', () => {
    logger.info({ port: config.WORKER_PORT }, 'Worker health server listening');
  });

  return server;
}
