import path from 'node:path';
import { adminBookingRoutes } from '@/modules/admin-booking/admin-booking.routes';
import { adminRoutes } from '@/modules/admin/admin.routes';
import { authRoutes } from '@/modules/auth/auth.routes';
import { complexRoutes } from '@/modules/complex/complex.routes';
import { courtRoutes } from '@/modules/court/court.routes';
import { passwordResetRoutes } from '@/modules/password-reset/password-reset.routes';
import { planRoutes } from '@/modules/plan/plan.routes';
import { publicBookingRoutes } from '@/modules/public-booking/public-booking.routes';
import { sportRoutes } from '@/modules/sport/sport.routes';
import { userRoutes } from '@/modules/user/user.routes';
import type { AppEnv } from '@/types/hono';
import type { Hono } from 'hono';
import { serveStatic } from 'hono/bun';
import { registerEventsRoutes } from './lib/sse';
import { healthCheckRoutes } from './modules/health-check/health-check.routes';

export function registerRoutes(app: Hono<AppEnv>) {
  app
    .route('', authRoutes)
    .route('/api/admin', adminRoutes)
    .route('/api/user', userRoutes)
    .route('/api/plans', planRoutes)
    .route('/api/password-reset', passwordResetRoutes)
    .route('/api/complexes', complexRoutes)
    .route('/api/sports', sportRoutes)
    .route('/api/courts', courtRoutes)
    .route('/api/public-bookings', publicBookingRoutes)
    .route('/api/admin-bookings', adminBookingRoutes)
    .route('/api/health', healthCheckRoutes);

  registerEventsRoutes(app);

  app.use('*', serveStatic({ root: './public' }));
  app.get('*', async (c) => {
    if (c.req.path === '/api' || c.req.path.startsWith('/api/')) {
      return c.notFound();
    }

    // Keep real asset URLs as 404s if the file does not exist.
    if (path.extname(c.req.path)) {
      return c.notFound();
    }

    const indexFile = Bun.file('./public/index.html');
    if (!(await indexFile.exists())) {
      return c.notFound();
    }

    return c.html(await indexFile.text());
  });
}
