import cors from 'cors';
import express from 'express';
import { config } from './config.js';
import { migrate } from './db.js';
import { requireAuth } from './auth.js';
import { startJobPoller } from './jobPoller.js';
import { authRouter } from './routes/auth.js';
import { nodesRouter } from './routes/nodes.js';
import { operationsRouter } from './routes/operations.js';
import { proxyRouter } from './routes/proxy.js';
import { schedulesRouter } from './routes/schedules.js';
import { startScheduler } from './scheduler.js';

migrate();

const app = express();

app.use(cors({
  origin(origin, callback) {
    if (!origin || config.corsOrigins.includes(origin)) {
      callback(null, true);
      return;
    }
    callback(new Error('CORS origin is not allowed.'));
  },
  credentials: true,
}));
app.use(express.json());

app.use('/api/auth', authRouter);
app.use('/api', requireAuth, proxyRouter);
app.use('/api/nodes', requireAuth, nodesRouter);
app.use('/api/operations', requireAuth, operationsRouter);
app.use('/api/schedules', requireAuth, schedulesRouter);

app.use((error, _req, res, _next) => {
  const status = error.status || 500;
  res.status(status).json({ error: error.message || 'Internal server error.' });
});

app.listen(config.port, () => {
  console.log(`Incus backup management API listening on http://localhost:${config.port}`);
});

startScheduler();
startJobPoller();
