import express from 'express'
import cors from 'cors'
import { existsSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { config } from './config.js'
import apiRouter from './routes/index.js'

const __dirname = dirname(fileURLToPath(import.meta.url))

const app = express()
app.use(cors())
app.use(express.json({ limit: '1mb' }))

// Visi API maršrutai po /api.
app.use('/api', apiRouter)

// Produkcijoje serveris atiduoda ir sukompiliuotą UI (web/dist),
// kad mazgas veiktų kaip vienas atsisiunčiamas paketas.
const webDist = resolve(__dirname, '..', '..', 'web', 'dist')
if (existsSync(webDist)) {
  app.use(express.static(webDist))
  app.get('*', (_req, res) => {
    res.sendFile(resolve(webDist, 'index.html'))
  })
} else {
  app.get('/', (_req, res) => {
    res.type('text').send(
      'TCP: A.R.K.A. API veikia. UI dar nesukompiliuotas — paleiskite `npm run dev`.\n' +
        'TCP: A.R.K.A. API is running. Build the UI or run `npm run dev`.'
    )
  })
}

app.listen(config.port, config.host, () => {
  console.log(
    `[A.R.K.A.] Mazgas paleistas / node up — http://${config.host}:${config.port} (${config.env})`
  )
})
