import 'dotenv/config'
import { buildPublicApp } from './app.public.js'
import { buildInternalApp } from './app.internal.js'
import { autoOfflineStaleMitras } from './services/mitra-status.service.js'
import { initFirebase } from './plugins/firebase.js'
import { restoreActiveTimers } from './services/session-timer.service.js'

const PUBLIC_PORT = process.env.PUBLIC_PORT || 3000
const INTERNAL_PORT = process.env.INTERNAL_PORT || 3001
const INTERNAL_HOST = process.env.INTERNAL_HOST || '127.0.0.1'

const start = async () => {
  initFirebase()
  const publicApp = await buildPublicApp()
  const internalApp = await buildInternalApp()

  await publicApp.listen({ port: PUBLIC_PORT, host: '0.0.0.0' })
  console.log(`Public API listening on port ${PUBLIC_PORT}`)

  await internalApp.listen({ port: INTERNAL_PORT, host: INTERNAL_HOST })
  console.log(`Internal API listening on ${INTERNAL_HOST}:${INTERNAL_PORT}`)

  // Restore session timers for active sessions (on server restart)
  await restoreActiveTimers()

  // Auto-offline mitras with stale heartbeat (every 30s)
  setInterval(async () => {
    try {
      const count = await autoOfflineStaleMitras()
      if (count > 0) console.log(`Auto-offlined ${count} stale mitra(s)`)
    } catch (err) {
      console.error('Auto-offline check failed:', err)
    }
  }, 30_000)
}

start().catch((err) => {
  console.error(err)
  process.exit(1)
})
