import express from 'express';
import cors from 'cors';
import { login } from './services/unifiClient.js';
import { loadPolicies } from './services/policyEngine.js';
import { loadTimers } from './services/timerService.js';
import { loadCurfew } from './services/curfewService.js';
import policiesRouter from './routes/policies.js';
import devicesRouter from './routes/devices.js';
import timersRouter from './routes/timers.js';
import curfewRouter from './routes/curfew.js';
import rulesRouter from './routes/rules.js';

const app = express();
const PORT = 3001;

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

app.use('/api/policies', policiesRouter);
app.use('/api/devices', devicesRouter);
app.use('/api/timers', timersRouter);
app.use('/api/curfew', curfewRouter);
app.use('/api/rules', rulesRouter);

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', timestamp: Date.now() });
});

async function startup() {
  console.log('[BarkWho] Starting backend...');

  // Load persistent state first
  loadPolicies();
  loadTimers();
  loadCurfew();

  // Attempt UDR authentication (non-blocking if no creds)
  const authed = await login();
  if (!authed) {
    console.warn('[BarkWho] Running without UDR connection - configure .env to connect');
  }

  app.listen(PORT, '0.0.0.0', () => {
    console.log(`[BarkWho] Backend listening on port ${PORT}`);
  });
}

startup().catch((err) => {
  console.error('[BarkWho] Startup failed:', err);
  process.exit(1);
});
