const express = require('express');
const cors = require('cors');
const { AppError } = require('./utils/helpers');
const authRoutes = require('./routes/auth.routes');
const deviceRoutes = require('./routes/device.routes');
const ingestRoutes = require('./routes/ingest.routes');

const app = express();

app.use(cors());
app.use(express.json());

app.get('/', (_req, res) => {
  res.json({ ok: true, service: 'vtrack-api' });
});

app.get('/health', (_req, res) => {
  res.json({ ok: true, service: 'vtrack-api' });
});

app.use('/auth', authRoutes);
app.use('/', deviceRoutes);
app.use('/ingest', ingestRoutes);

app.use((err, _req, res, _next) => {
  const status = err instanceof AppError ? err.status : 500;
  if (status >= 500) console.error(err);
  res.status(status).json({ error: err.message || 'Server error' });
});

module.exports = app;
