import express, { type Express } from 'express'
import type { StaticWebsiteConfig } from './static-site'
import { shouldServeSpaFallback } from './static-site'

export function registerStaticWebsiteRoutes(app: Express, staticWebsiteConfig: StaticWebsiteConfig) {
  if (!staticWebsiteConfig.enabled) {
    return
  }

  app.use(express.static(staticWebsiteConfig.distPath, {
    fallthrough: true,
    index: false,
  }))

  app.get('*', (req, res, next) => {
    if (!shouldServeSpaFallback(req.path)) {
      next()
      return
    }

    res.sendFile(staticWebsiteConfig.indexHtmlPath)
  })
}
